C++ 如何正确地解析子字符串,以便它们对我的新手计算器有效?
如果可能的话,请ELI5,因为我只编写了几天的代码,这是我的第一个程序!下面是我脚本的一部分,它应该解释某人输入的一行输入(比如“5+5”之类) 我还想在以后添加其他格式不同的操作,这就是为什么我使用string而不是switch函数之类的东西 无论如何。。这不起作用:(下面是我的逻辑过程,也许有人能指出我哪里搞砸了?:) 提前谢谢你C++ 如何正确地解析子字符串,以便它们对我的新手计算器有效?,c++,substring,calculator,C++,Substring,Calculator,如果可能的话,请ELI5,因为我只编写了几天的代码,这是我的第一个程序!下面是我脚本的一部分,它应该解释某人输入的一行输入(比如“5+5”之类) 我还想在以后添加其他格式不同的操作,这就是为什么我使用string而不是switch函数之类的东西 无论如何。。这不起作用:(下面是我的逻辑过程,也许有人能指出我哪里搞砸了?:) 提前谢谢你 if (fork.find("+" && "-" && "x" && "/")) { size_t
if (fork.find("+" && "-" && "x" && "/"))
{
size_t pos = fork.find("+" && "-" && "x" && "/"); // Defines a position at the operator symbol
string afterfork = fork.substr(pos + 1); // Cuts a substring at the operator symbol + 1
size_t beforepos = fork.find_first_of(fork); // Defines a position at the beginning of the string
string beforefork = fork.substr(beforepos); // cuts a substring at the begninning of the string
string atfork = fork.substr(pos); // cuts a substring that only has one char (the operator +, -, x, etc)
int x = stoi(beforefork.c_str()); // converts the first substring to an integer
int y = stoi(afterfork.c_str()); // converts the third substring to an integer
string operation = atfork; // converts the middle substring that only has one char to a different name.
return input(x, operation, y); // will send this information to the input function (which will do the math for the calculator).
}
要在字符串中搜索字符列表中的一个,可以使用。如果未找到任何内容,此函数将返回
const size_t operatorPos = input.find_first_of("+-*/");
if (operatorPos == std::string::npos) {
std::cout << "Couldn't find an operator!\n";
return;
}
要将字符串转换为整数,有很多选项。我将使用这个答案。这个函数是一个异常,当它不能将字符串转换为整数时,我们需要处理它
int leftInt;
try {
leftInt = std::stoi(left);
} catch (...) {
std::cout << '"' << left << "\" is not a valid integer!\n";
return;
}
int rightInt;
try {
rightInt = std::stoi(right);
} catch (...) {
std::cout << '"' << right << "\" is not a valid integer!\n";
return;
}
在这种情况下,您将不会收到类似“five”不是有效整数这样的错误消息代码>。您将得到如下结果:
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
Abort trap: 6
试着运行std::stoi(“五”)
自己看看
请不要使用名称空间std代码> 如果这是您的第一个计划,那么我建议您尝试更简单的方法。我的意思是,即使你已经编程多年了,解析还是很棘手的。你的程序有很多问题。空白是免费的。。。我不确定如果(fork.find(“+”&&“-”&&&“x”&&&“/”)应该做什么。fork
astd::string
?
const int leftInt = std::stoi(left);
const int rightInt = std::stoi(right);
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
Abort trap: 6