C++ 从 cin 读取输入,直到读取整行

标签 c++ input eof cin

我有一个 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();

ba 在这里是同一个数字,你应该在获取第二个数字之前调用 pop() ,比如:

if (count>1)
{
    b =  num.top();
    num.pop();
    a = num.top();
    num.pop();

关于C++ 从 cin 读取输入,直到读取整行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23947833/

相关文章:

c++ - 如何克服 double 不准确?

c++ - 具有邻接表的有向图的复制构造函数

html - CSS - 搜索框重叠 div 的填充

c++ - 如何使用 POSIX 在 C++ 中执行命令并获取命令的输出?

C++ STL 映射,其键为 shared_ptr<struct tm>

linux - 如何将参数传递给 shell 脚本

text - 自定义TextEdit,当它变宽时如何隐藏TextInput

python - 无法导入第三方库python3

C++ std::getline() 不设置 EOF 标志

c++ - EOF 在 Windows 上并不总是 ^Z?