zhangsongcui

poj.openjudge.cn/practice/1001

Feb 5th, 2012
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. #include <iostream>
  2. #include <cctype>
  3. #include <stack>
  4. #include <cassert>
  5. #include <string>
  6.  
  7. int main()
  8. {
  9.     using namespace std;
  10.     char c;
  11.     stack<char> symbol;
  12.     while (cin.get(c) && isalpha(c))
  13.         cout << c;
  14.     cin.putback(c);
  15.     cout << ' ';
  16.  
  17.     string sth;
  18.     bool flag = false;
  19.     while ( (cin >> c) && (c != ';')) {
  20.         if (c == ')') {
  21.             flag = true;
  22.             while (true) {
  23.                 assert(!symbol.empty() && "括号不匹配");
  24.                 switch (symbol.top())
  25.                 {
  26.                 case '*': cout << "->"; break;
  27.                 case 'c': cout << "const"; break;
  28.                 case '(': goto EXIT;
  29.                 default : assert(false && "未知字符");
  30.                 }
  31.                 symbol.pop();
  32.             }
  33. EXIT:
  34.         symbol.pop();
  35.         } else if (flag) {
  36.             if (c == '(') {
  37.                 cout << c;
  38.                 int count = 1;
  39.                 while (count != 0) {
  40.                     cin >> c;
  41.                     if (c == '(')
  42.                         ++count;
  43.                     else if (c == ')')
  44.                         --count;
  45.                     cout << c;
  46.                 }
  47.             } else {
  48.                 cout << c;
  49.             }
  50.         } else {
  51.             if (c == '*' || c == '(') {
  52.                 symbol.push(c);
  53.             } else {
  54.                 assert((isalnum(c) || c=='_') && "非标识符");
  55.                 sth = c;
  56.                 while (c = cin.peek(), isalnum(c) || c=='_') {
  57.                     cin.ignore();
  58.                     sth.push_back(c);
  59.                 }
  60.                 if (sth == "const") {
  61.                     symbol.push('c');
  62.                 } else {
  63.                     cout << sth << ':';
  64.                     flag = true;
  65.                 }
  66.             }
  67.         }
  68.     }
  69.     while (!symbol.empty()) {
  70.         switch (symbol.top()) {
  71.             case 'c': cout << "const"; break;
  72.             case '*': cout << "->"; break;
  73.             case '(': assert(false && "括号不匹配"); break;
  74.             default : assert(false && "未知字符");
  75.         }
  76.         symbol.pop();
  77.     }
  78.     cout << ';' << endl;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment