有没有办法我可以从 istringstream 中读取两个字符
Is there a way I can read two char from the 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
.
我预计 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。
类型的表达式{in >> num}
,解析流中的字符序列(直到第一个空格或行尾(并将它们解释为整数值。
而不是用
一位数读取
if (isdigit(num)) {
postFixStack.push(in.get());
}
以整数值读取:
if (isdigit(num)) {
int number;
in >> number;
postFixStack.push(number);
}
相关文章:
- 查找字符在两个索引之间出现的次数
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 函数返回两个字符串的第一个常用字符
- 在函数中连接两个字符,并在 C++ 中返回输出
- 为什么要更改这两个代码的输出"&"字符?
- 舍入 QDecDouble 值,精度最多为两个字符
- 计算两个字符序列
- 在c++中连接两个字符
- 查找和比较两个字符串中的字符
- 为什么C++中不允许连接两个常量字符*?
- 如何使用排序和比较这两个函数在 c++ 中对字符数组进行排序?
- 有没有办法我可以从 istringstream 中读取两个字符
- 如何查找两个字符串 c++ 中常用字符的数量
- 如何查看两个字符变量是否相等
- 使用位于 C 字符串中的两个字符*获取子字符串
- C++ std::string 中是否有任何函数可以计算两个字符串的相同起始字符的总数或任何最佳方法
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- 比较两个字符的问题
- 如何修复密码条目,它一次输入两个字符