有没有办法可以从istringstream中读取两个char?

时间:2019-07-27 20:25:16

标签: c++ stack

我试图编写一个函数postFixEval,用于基于堆栈的后缀表达式求值。该程序读取后缀表达式并打印其值。每个输入表达式都在其自己的行上输入,并且当用户输入空白行时,程序将终止。假设只有二进制运算,并且表达式不包含变量。我正在使用堆栈。

示例

50 6 +

89 6 + 9 2 - /

当前,我正在尝试仅解决加法函数,即: 1 2 +

当我尝试使用一位数字时,我得到了正确的加值,但是我无法使用两位数字。


#include <iostream>
#include <string>
#include <sstream>
#include <stack>
#include <cctype>

using namespace std;

//skipWhiteSpace for skipping whitespace in an input stream

void skipWhiteSpace(istream& in)
{
    while (in.good() && isspace(in.peek()))
    {
        // Read and discard the space character
        in.ignore();
        in.get();
    }
}

int postFixEval(string str)
{
    istringstream in = istringstream(str);
    stack<int> postFixStack;
    skipWhiteSpace(in);

    while (in)
    {
        int num = in.peek();

        //checking if the instream is a digit or not
        if (isdigit(num)) {
            postFixStack.push(in.get());
        }
        else {

            char op = in.get();
            if (op == '+') {

                int num1 = postFixStack.top();
                num1 = num1 - '0';
                postFixStack.pop();

                int num2 = postFixStack.top();
                num2 = num2 - '0';
                postFixStack.pop();

                postFixStack.push(num1 + num2);
            }
        }
    }
    return postFixStack.top();
}

int main()
{
    string input;

    while (true)
    {
        cout << "Enter a postfix expression, or press ENTER to quit:\n";
        getline(cin, input);

        if (input.length() == 0)
        {
            break;
        }
        int number = postFixEval(input);
        cout << "The value of " << input << " is " << number << endl;
    }

    return 0;
}

我希望78 5 +的输出为83。但是我得到13

2 个答案:

答案 0 :(得分:1)

而不是用

读一位
    if (isdigit(num)) {
        postFixStack.push(in.get());
    }

读取整数值:

    if (isdigit(num)) {
        int number;
        in >> number;
        postFixStack.push(number);
    }

答案 1 :(得分:1)

  

我希望78 5 +的输出为83。但是我得到的是13。

之所以会这样,是因为您将数字而不是数字放入堆栈中。因此,到达运算符+堆栈后,其状态为{7,8,5}。弹出最后两个元素(5和8),得到13 = 5 + 3。

要解决此问题,只需使用stack<int>来存储数字:

int postFixEval(string str)
{
    istringstream in = istringstream(str);
    stack<int> postFixStack;
    skipWhiteSpace(in);

    while (in)
    {
        char ch = in.peek();
        if (isdigit(ch)) {
            int num;
            in >> num;
            postFixStack.push(num);
        }
        else {
            char op = in.get();
            if (op == '+') {
                int num1 = postFixStack.top();
                postFixStack.pop();
                int num2 = postFixStack.top();
                postFixStack.pop();
                postFixStack.push(num1 + num2);
            }
        }
    }
    return postFixStack.top();
}

UPD:让我解释一下peek()operator>>()之间的区别。

1)Peek返回流中的下一个字符,而不提取它。因此,如果流包含'78',peek()将返回字符'7'的整数代码,它等于55。

2)Operator>>(在表达式{in >> num}中使用整数类型),解析流中的字符序列(直到第一个空格或行尾),并将其解释为整数值。 / p>

相关问题