【发布时间】:2023-03-26 20:22:01
【问题描述】:
我正在制作一个将中缀数学字符串转换为后缀的函数。 这就是我所拥有的:
std::string toPostfix(std::string& infixStr, std::string& postfixStr, std::string& first_nr, std::string& second_nr, char oper, char prev_oper) {
//std::cout << "[" << infixStr << "]" << std::endl;
if (infixStr == "") {
if (second_nr == "") {
second_nr = "0";
}
if (oper == '\0') {
oper = prev_oper;
if (prev_oper == '-') {
second_nr = first_nr;
first_nr = "0";
}
}
postfixStr += first_nr + " " + second_nr + " " + oper;
std::cout << " end: " << postfixStr << std::endl ;
return postfixStr;
}
char c = infixStr[0];
if (isOperator(c)) {
///////////////
if (postfixStr == "") {
if (c == '-') {
}
}
//////////////////
if (oper != '\0') {
if (first_nr == "") {
if (oper == '-') {
/////////////////////////
}
}
postfixStr += first_nr + " " + second_nr + " " + oper + " ";
first_nr = "";
second_nr = "";
oper = '\0';
prev_oper = c;
} else {
oper = c;
}
} else {
if (oper == '\0') {
first_nr += c;
} else {
second_nr += c;
}
}
infixStr = infixStr.erase(0, 1);
return toPostfix(infixStr, postfixStr, first_nr, second_nr, oper, prev_oper);
}
这在某些情况下有效,但是例如此输入字符串0+1-5+2 输出为0 1 + 5 2 +。 - 被忽略。正确的输出应该是0 1 + -5 2 + 我做错了什么?我认为我需要区分运算符中的减号,以及使值变为负数时的减号。
【问题讨论】:
-
我建议您阅读this,并重新考虑您发布的整个代码。这不是您应该将中缀转换为后缀的方式。试图在这里和那里修补东西,然后在其他地方出现泄漏——这就是你编写代码的路径。
标签: c++ postfix-notation