有没有办法我可以从 istringstream 中读取两个字符

Is there a way I can read two char from the istringstream?

本文关键字:字符 两个 读取 我可以 istringstream 有没有      更新时间:2023-10-16

我正在尝试编写一个函数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.

我预计 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},解析流中的字符序列(直到第一个空格或行尾(并将它们解释为整数值。

而不是用

一位数读取

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

以整数值读取:

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