我正在尝试使用 C 实现 RPN 计算器。以下是代码:
float rpn(void) {
float ans = 0;
int top = -1;
float stack[50];
char expression[100];
char *token;
float newnumber;
float operand1, operand2;
int i;
printf("Enter RPN statement here: \n");
scanf("%s", expression);
/* get the first token */
token = strtok(expression, " ");
/* walk through other tokens */
while (token != NULL) {
if (isdigit(*token)) {
newnumber = atof(token);
push(stack, &top, newnumber);
} else {
if (top < 1) {
printf("Error: Not enough operands to perform the operation!\n");
return ans;
} else {
operand1 = pop(stack, &top);
operand2 = pop(stack, &top);
newnumber = evaluate(token, operand1, operand2);
push(stack, &top, newnumber);
ans = newnumber;
}
}
token = strtok(NULL, " ");
printf("\nCurrent stack is: \n");
for (i = 0; i <= top; i++) {
printf("%f\n", stack[i]);
}
printf("\n");
}
return ans;
}
float pop(float* stack, int* top) {
float ans;
ans = stack[*top];
(*top)--;
return ans;
}
int push(float* stack, int* top, float n) {
(*top)++;
stack[*top] = n;
return 0;
}
float evaluate(char* operator, float x, float y) {
float ans;
if (strcmp(operator, "+") == 0) {
ans = x + y;
}
if (strcmp(operator, "-") == 0) {
ans = x - y;
}
if (strcmp(operator, "*") == 0) {
ans = x * y;
}
if (strcmp(operator, "/") == 0) {
ans = x / y;
}
return ans;
}
问题是,当在 strtok() 函数中使用逗号或句号作为分隔符时,它可以工作,但使用空格时,它只能读取第一个标记。
有什么帮助吗?
谢谢