我有一个 while 循环读取一个 char 'c',我检查该 char 是否是一个运算符; “+”、“-”、“/”或“*”。 while 循环逐个字符地读取,但它不会停止……例如,如果输入的最后一个字符是“+”。它将永远留在循环中,字符“c”设置为“+”。
stack<int> num;
char c;
int n,count=0,a,b;
while (cin>>c)
{
if (c != '+' && c != '-' && c != '/' && c != '*')
{
cout << c << endl;
n = (c - 48);
num.push(n);
cin >> c;
count++;
}
else if (c == '+' || c == '-' || c == '/' || c == '*')
{
cout << "count is " << count << endl;
if (count>1)
{
b = num.top();
a = num.top();
num.pop();
num.pop();
if (c == '+')
{
num.push(a+b);
count--;
}
else if (c == '-')
{
num.push(a+b);
count--;
}
else if (c == '/')
{
if (b != 0)
{
num.push(a/b);
count--;
}
else
{
cout << "division by zero" << endl;
return(0);
}
}
else if (c == '*')
{
num.push(a*b);
count--;
}
else
{
cout << "invalid input" << endl;
return(0);
}
}
else
{
cout << "stack underflow" << c << endl;
return(0);
}
}
cout << c << endl;
}
}
最佳答案
既然您澄清了您的问题,它就更清楚了。 @TeoZec 的回答应该是正确的。我只想注意您上面的代码中有两点似乎有问题:
else if (c == '-')
{
num.push(a+b);
count--;
}
在这里您可能需要 a-b
。
if (count>1)
{
b = num.top();
a = num.top();
num.pop();
num.pop();
b
和 a
在这里是同一个数字,你应该在获取第二个数字之前调用 pop()
,比如:
if (count>1)
{
b = num.top();
num.pop();
a = num.top();
num.pop();
关于C++ 从 cin 读取输入,直到读取整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23947833/