我在C++中编写了一个函数式函数。我的问题是否相当简单。我正在阅读一个文件“4 + 5”。所以我把它存储成一个字符串。如何将字符串转换为数学公式
我的问题:
我该如何输出9?因为如果我只是cout < < myString ...输出只是“4 + 5”
我在C++中编写了一个函数式函数。我的问题是否相当简单。我正在阅读一个文件“4 + 5”。所以我把它存储成一个字符串。如何将字符串转换为数学公式
我的问题:
我该如何输出9?因为如果我只是cout < < myString ...输出只是“4 + 5”
您可能需要做一些比您期望的更多的工作。您需要将每个操作数和运算符分别读入字符串变量。接下来,一旦确认它们确实是整数,将数字字符串转换为整数。你可能会有一个角色里面有操作数,你会做一些类似开关的情况来确定实际的操作数是什么。从那里开始,您需要根据变量中存储的值执行开关箱中确定的操作并输出最终值。
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char* argv[])
{
std::string s = "4 + 5";
std::istringstream iss;
iss.str(s); // fill iss with our string
int a, b;
iss >> a; // get the first number
iss.ignore(10,'+'); // ignore up to 10 chars OR till we get a +
iss >> b; // get next number
// Instead of the quick fix I did with the ignore
// you could >> char, and compare them till you get a +, - , *, etc.
// then you would stop and get the next number.
// if (!(iss >> b)) // you should always check if an error ocurred.
// error... string couldn't be converted to int...
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << a + b << std::endl;
return 0;
}
你的输出是 “4 + 5”,因为 “4 + 5” 是像任何其他字符串例如: “ABC”,而不是4和5是整数,+是操作员。 如果它涉及的不仅仅是添加2个数字,还可以将您的中缀表达式转换为使用堆栈表达和评估的后缀。
如果你正在寻找一个快速的方法来做到这一点,我不认为有一个。你几乎必须从头开始编写它,这是大学级别的东西。 – immibis
@immibis那么,取决于你需要什么。 '+,*,()'的递归下降解析器没有花哨的错误处理,非常简单。弗雷德溢出做了一个视频,顺便说一句。但就目前来看,这个问题当然太广泛了。 –
你的公式总是两个数字的总和吗? – d40a