首页 > 解决方案 > 有没有办法从 istringstream 中读取两个字符?

问题描述

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

例子,

50 6 +

89 6 + 9 2 - /

目前我正在尝试仅解决加法功能,即: 1 2 +.

当我尝试使用一位数字时,我得到了正确的附加值,但是我无法使用 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

标签: c++stack

解决方案


而不是读取单个数字

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

读入一个整数值:

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

推荐阅读