fork download
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. using namespace std;
  5.  
  6. typedef unsigned char uchar;
  7.  
  8. enum Token {
  9. TkMD = 'M' | 'D' << 8,
  10. TkRP = 'R' | 'P' << 8,
  11. TkTP = 'T' | 'P' << 8,
  12. TkTT = 'T' | 'T' << 8
  13. };
  14.  
  15. inline Token tokenize(uchar c0, uchar c1) { return (Token)(c0 | c1 << 8); }
  16.  
  17. bool parse(istream &in)
  18. {
  19. for (;;) {
  20. // read command (2 chars)
  21. char cmd[2];
  22. if (in >> cmd[0] >> cmd[1]) {
  23. //cout << "DEBUG: token: " << hex << tokenize(cmd[0], cmd[1]) << endl;
  24. switch (tokenize(cmd[0], cmd[1])) {
  25. case TkMD: { // MD<num>
  26. int num;
  27. if (in >> num) {
  28. cout << "Received 'MD" << dec << num << "'." << endl;
  29. } else {
  30. cerr << "ERROR: Number expected after 'MD'!" << endl;
  31. return false;
  32. }
  33. } break;
  34. case TkRP: { // RP<num>
  35. int num;
  36. if (in >> num) {
  37. cout << "Received 'RP" << dec << num << "'." << endl;
  38. } else {
  39. cerr << "ERROR: Number expected after 'MD'!" << endl;
  40. return false;
  41. }
  42. } break;
  43. case TkTP: // TP
  44. cout << "Received 'TP'." << endl;
  45. break;
  46. case TkTT: // TT
  47. cout << "Received 'TT'." << endl;
  48. break;
  49. default:
  50. cerr << "ERROR: Wrong command '" << cmd[0] << cmd[1] << "'!" << endl;
  51. return false;
  52. }
  53. } else {
  54. cerr << "ERROR: Command expected!" << endl;
  55. return false;
  56. }
  57. // try to read separator
  58. char sep;
  59. if (!(in >> sep)) break; // probably EOF (further checks possible)
  60. if (sep != ',') {
  61. cerr << "ERROR: ',' expected!" << endl;
  62. return false;
  63. }
  64. }
  65. return true;
  66. }
  67.  
  68. int main()
  69. {
  70. // test string
  71. string sample("MD1,TP,RP5,TT,RP10");
  72. // read test string
  73. istringstream in(sample);
  74. if (parse(in)) cout << "Done." << endl;
  75. else cerr << "Interpreting aborted!" << endl;
  76. // done
  77. return 0;
  78. }
Success #stdin #stdout 0s 4556KB
stdin
Standard input is empty
stdout
Received 'MD1'.
Received 'TP'.
Received 'RP5'.
Received 'TT'.
Received 'RP10'.
Done.