[英]C Extract Infix (char array) and cast to int
给定一个字符串/字符数组,例如:
99+(88-77)*(66/(55-44)+33)
如何提取数字和运算符?
我想将它们存储到两个堆栈 a 和 b 中,每个堆栈只包含数字和运算符。
我不确定逻辑,我正在考虑扫描字符数组中的每个字符,将字符(数字)添加到另一个字符中,直到遇到运算符。 然后我转到 char(number) 并连接字符串。
有没有更好的方法来做到这一点,最好没有外部库?
正如评论中所指出的,您可以尝试使用strtol
从输入字符串中扫描整数。 我尝试了建议的方法,对于提供的测试用例,它似乎对我有用。 我还没有针对极端情况对此进行测试,但这应该能让您更好地了解评论中的用户在说什么:
int main() {
char input[30] = "99+(88-77)*(66/(55-44)+33)";
// Initialize Stack Indices
operandStackIndex = 0;
operatorStackIndex = 0;
// Our markers for strtol()
char *pStart = input;
char *pEnd;
long ret;
while ((ret = convertStringToLong(pStart, &pEnd, 10)) > 0) {
operandStack[operandStackIndex++] = ret;
pStart = pEnd;
while (isOperator(*pStart)) { // Check whether character it '+','-','/','(',')','*'..
operatorStack[operatorStackIndex++] = *pStart;
pStart++;
}
}
printf("Operand Stack:\n");
for (int i = operandStackIndex - 1; i >= 0; i--)
printf("%d\n", operandStack[i]);
printf("Operator Stack:\n");
for (int i = operatorStackIndex - 1; i >= 0; i--)
printf("%c\n", operatorStack[i]);
}
这是convertStringToLong
方法的简单实现(替代strtol
):
long convertStringToLong(char* pStart, char** pEnd, int base) {
long num = 0;
while (isDigit(*pStart)) {
num = num * base + (*pStart - '0');
pStart++;
}
*pEnd = pStart;
return num;
}
当我运行这个时,我能够看到预期的输出:
Operand Stack:
33
44
55
66
77
88
99
Operator Stack:
)
+
)
-
(
/
(
*
)
-
(
+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.