【发布时间】:2014-05-30 05:43:23
【问题描述】:
我在一个字符'c'中读取了一个while循环,我检查了这个字符是否是一个运算符; “+”、“-”、“/”或“*”。 while 循环逐个字符地读取,但它不会停止……例如,如果输入的最后一个字符是“+”。它将永远留在循环中,将 char '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 他在那里不需要 break 语句,条件应该可以正常工作。
-
为什么不使用getline?
getline(cin, string)然后做点什么? -
当没有更多输入时它不会停止,如果输入行中的最后一个字符是“+”,那么它会一直停留在 while 循环中使用“+”进行计算,而不是读完所有内容后退出。
-
@user3678093 你能发布更多代码吗?