2014-07-19 110 views
0

嗨,大家好,我在加入输入时遇到了加号困难。这里即时处理反向波兰符号计算器。我所要做的就是将输入作为“3 2 + $”,这意味着(以简单的方式)添加3和2并显示它们。我尝试使用stringstreams,而(cin)。现在我试图逐个输入;加号逃脱C++

int num; 
char ch; 
while (cin) 
    { 
     if (cin >> num) 
     { 
      cout<<num; 
     } 
     else 
     { 
      cin.clear(); 
      cin >> ch; 
      cout << ch; 
     } 
    } 
} 

它不适用于+和 - 并适用于*和/。但我也需要这些操作数。我尝试通过getline来尝试istringstream。它没有看到+或 - 或者。

+0

你认为+和 - 之前可以是数字的一部分:-10仍然是一个整数... –

+0

获取每个参数为一个字符串,测试字符串是什么样的参数。 – jxh

+0

'std :: cin >> num'只有在提取+或 - 后才会失败,并意识到没有以下编号。 – chris

回答

2

在你的示例代码中,这行代码让我担心while (cin)(必须确定你有和无限循环),在示例代码下面(我补充说,当输入一个空行时程序结束)。

CIN将由一个词,当你调用cin >> somevariable;获取输入一个词,当你在控制台3 2 + $写会得到4个结果:然后然后+和最后$。阅读波兰标记时的其他问题是,您无法预测下一个标记是数字还是运算符,您可以得到:3 2 + $,但也可以使用3 2 2 + * $。出于这个原因,你需要一个容器来存储操作数。

这里是一个小工作示例:

#include <iostream> 
#include <stack> 
#include <boost/lexical_cast.hpp> 

using namespace std; 

int main(int argc, char *argv[]) { 
    string read; 
    std::stack<int> nums; 
    while (cin >> read) { 
     if (read.empty()) { 
      break; 
     } 
     else if (read == "$") { 
      std::cout << nums.top() << std::endl; 
     } 
     else if (read == "+" || read == "-" || read == "*" || read == "/") { 
      if (nums.size() < 2) { 
      } // error code here 

      int n1 = nums.top(); 
      nums.pop(); 
      int n2 = nums.top(); 
      nums.pop(); 

      if (read == "+") 
       nums.push(n2 + n1); 
      if (read == "-") 
       nums.push(n2 - n1); 
      if (read == "*") 
       nums.push(n2 * n1); 
      if (read == "/") 
       nums.push(n2/n1); 
     } 
     else { 
      try { 
       nums.push(boost::lexical_cast<int>(
        read)); // you should add convertion excepcion code 
      } 
      catch (...) { 

      } 
     } 
    } 

    return 0; 
}