我正在尝试编写一个RPN计算器,其中这一行输入为一个简单的例子: 2 3 + 会打印: 五 然后结束。
我需要程序取输入线,将数字放在堆栈上,找到非数字,检查它们是否为运算符:'+',' - ','/'或'*'如果然后他们计算堆栈中最后两个数字的计算,删除这两个数字,然后将新数字添加到堆栈中。这需要从左到右,通过输入行解析。此外,如果符号不是其中一个操作符,它应该打印到cout。
目前,程序在编译时会将很长的错误代码列表转储到屏幕上。
这就是我所拥有的:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
stack<int> num;
string line;
int n,count=0,a,b;
char c;
while (getline(cin,line))
{
for (string::const_iterator it = line.begin(); it != line.end(); ++ it)
{
if (isdigit(static_cast<unsigned char>(*it)))
{
cout << it << endl;
n = (it - 48);
num.push(n);
count++;
}
else if (ispunct(static_cast<unsigned char>(*it)))
{
if (it == '+' || it == '-' || it == '/' || it == '*')
{
cout << "count is " << count << endl;
if (count>1)
{
b = num.top();
num.pop();
a = num.top();
num.pop();
if (it == '+')
{
cout << "+" <<endl;
num.push(a+b);
count--;
}
else if (it == '-')
{
num.push(a-b);
count--;
}
else if (it == '/')
{
if (b != 0)
{
num.push(a/b);
count--;
}
else
{
cout << "division by zero" << endl;
return(0);
}
}
else if (it == '*')
{
num.push(a*b);
count--;
}
else
{
cout << "invalid input" << endl;
return(0);
}
}
else
{
cout << "stack underflow" << c << endl;
return(0);
}
}
cout << c << endl;
}
}
}
while ( !num.empty() )
{
cout << num.top() << endl;
num.pop();
}
return 0;
}
答案 0 :(得分:3)
编译器将错误转储到屏幕上
处理此错误的一般方法是阅读错误,了解他们指出的问题,然后修改程序以纠正问题。如果您不理解错误消息,那么首先要尝试的是在网络上搜索特定错误消息或错误消息中您不理解的任何特定字词。
如果在该研究之后,您仍然不了解特定的错误消息,那么可以向其他程序员询问该特定错误消息的解释。在这种情况下,您将向他们显示特定的错误消息以及错误引用的源代码行。
此外,从一开始就重要,列出第一个错误。这是因为早期的错误可能会使编译器混淆并导致它在之后产生更多错误,这可能没有多大意义。
您使用错误消息发布的文档似乎已开始切断。错误消息是否填满了控制台缓冲区,以至于您失去了开头?
当我使用gcc编译代码时,get错误消息以:
开头 main.cpp: In function 'int main()':
main.cpp:21:22: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
cout << it << endl;
^
如果你从头开始,那么从哪里开始寻找问题会更清楚。
为了防止编译器输出在开始时被切断,你可以做很多事情:
less
。head -n 20
之类的命令,这样您只能获得前几行输出,其余部分将被丢弃。在更正您看到的任何错误后,只需重新编译即可看到任何进一步的错误。答案 1 :(得分:1)
如果你在任何你想要一个字符的地方替换它,很多错误都可能会消失。将std :: const_iterator与字符进行比较可能是导致编译器出错的原因。
答案 2 :(得分:1)
您在it
的大多数使用中都错过了取消引用运算符(星号)。
您正在使用c
未初始化。
并且不要忘记为<cctype
和isdigit
添加ispunct
标题。