RPN计算器c++问题
RPN calculator c++ issues
我需要创建一个在输入文件上操作的RPN计算器。它使用4个标准算术运算符以及pow和%。我不知道为什么下面的程序不能为最后4个输入行工作。我得到了最后4行"语法错误"的输出。有什么想法或建议吗?我使用的示例输入.txt文件是:
5 * -
74 * 8 30 +
香蕉9 10 + 30 -
- 7 3-+ 2 -3+
40.65 900 -20 +
45.2 - 23.999%2
正确的输出应该是:
-17年7 语法错误语法错误-11年9 879.35 21.201100年#include<iostream>
#include<fstream>
#include<string>
#include<stack>
#include<sstream>
#include<math.h> //pow
#define SPACE(b) if (!(b)) throw "";
using namespace std;
double evalrpn(stack<string> & tkline);
int main(void){
string line;
ifstream inputfile;
string fileloc;
one:cout << "Enter the location of the input file: ";
getline(cin, fileloc);
inputfile.open(fileloc);
while (inputfile.fail())
{
cout << "The file at location " << fileloc << " failed to open." << endl;
goto one;
}
while (getline(inputfile, line)){
stack<string> tkline;
istringstream sstr(line);
string tk;
while (sstr >> tk)
tkline.push(tk);
if (!tkline.empty())
try {
auto z = evalrpn(tkline);
SPACE(tkline.empty());
cout << z << endl;
}
catch (...) { cout << "SYNTAX ERROR" << endl; }
}
cin.ignore();
return 0;
}
double evalrpn(stack<string> & tkline){
SPACE(!tkline.empty());
double x, y;
auto tk = tkline.top();
tkline.pop();
auto n = tk.size();
if (n == 1 && string("+-*/%'pow'").find(tk) != string::npos) {
y = evalrpn(tkline);
x = evalrpn(tkline);
if (tk[0] == '+') x += y;
else if (tk[0] == '-') x -= y;
else if (tk[0] == '*') x *= y;
else if (tk[0] == '/') x /= y;
else if (tk[0] == '%') x = fmod(x,y);
else pow(x, y);
}
else {
unsigned i; x = stod(tk, &i);
SPACE(i == n);
}
return x;
}
您的程序不会处理令牌之间没有空格的情况,因为istringstream
不会为您处理这种情况。您将不得不使用比按空格分割为标记更智能的解析器。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题