c++ - 有没有办法从 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
。
解决方案
而不是读取单个数字
if (isdigit(num)) {
postFixStack.push(in.get());
}
读入一个整数值:
if (isdigit(num)) {
int number;
in >> number;
postFixStack.push(number);
}
推荐阅读
- sql - SQL Server - 跳过“假”IF 语句,但仍需要通常的时间?
- react-native - react-native 中的 fetch() 函数抛出“网络请求失败”错误
- linux - dma_mmap_coherent() 映射内存的零拷贝用户空间 TCP 发送
- ajax - 如何在每页加载特定数量的记录并添加更多按钮
- spring - 如何搜索嵌套数组并仅使用 mongo 和 springdata 检索匹配的元素
- python - 使用 Prometheus 的 InfoMetricFamily 在 Grafana 中进行表格可视化
- excel - 如果密码不正确则关闭工作簿
- java - 获取 HTTP 状态 400-Bad Request REST
- python - 跨 ActiveMQ 代理网络负载平衡客户端连接
- javascript - 如何管理应用程序中的两种语言