如果可能,请ELI5,因为我只编码了几天,这是我的第一个程序!以下是我的脚本的一部分,该脚本应解释某人输入的单行输入(例如“ 5 + 5”或类似内容)。
我还有其他要添加的其他操作,它们的格式不同,这就是为什么我使用字符串而不是开关功能之类的原因。
反正..这是行不通的:(所以下面是我的逻辑过程,也许有人可以指出我搞砸的地方吗?:)]
谢谢您!
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).
}
要在字符串中搜索字符列表之一,可以使用find_first_of
。如果找不到任何内容,此函数将返回find_first_of
。
npos
要将字符串分成两个子字符串,可以使用npos
。要获得某个位置的字符,请使用const size_t operatorPos = input.find_first_of("+-*/");
if (operatorPos == std::string::npos) {
std::cout << "Couldn't find an operator!\n";
return;
}
。
substr
要把字符串转换成整数,有很多选择。我将使用substr
。此函数operator[]
是一个无法将字符串转换为整数的operator[]
异常。
const std::string left = input.substr(0, operatorPos);
const std::string right = input.substr(operatorPos + 1);
const char operation = input[operatorPos];
如果异常确实令人困惑(我花了很长时间才了解异常!),则可以尝试其他功能。我最喜欢的(也是IMO最好的)是std::stoi
。另一种选择是不捕获异常。
std::stoi
在那种情况下,您不会收到很好的错误消息。您会得到类似的内容:
throws
尝试运行catch,亲自看看!