C 带空间delimeter的strtok()函数
我正在尝试使用C实现RPN计算器。以下是代码:C 带空间delimeter的strtok()函数,c,strtok,rpn,C,Strtok,Rpn,我正在尝试使用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"
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;
}
浮动rpn(无效){
浮动ans=0;
int top=-1;
浮动堆栈[50];
字符表达式[100];
字符*令牌;
浮点数;
浮点操作数1,操作数2;
int i;
printf(“在此处输入RPN语句:\n”);
scanf(“%s”,表达式);
/*获取第一个令牌*/
token=strtok(表达式“”);
/*浏览其他代币*/
while(令牌!=NULL){
if(isdigit(*令牌)){
newnumber=atof(令牌);
推送(堆栈、顶部和新编号);
}否则{
如果(顶部<1){
printf(“错误:操作数不足,无法执行此操作!\n”);
返回ans;
}否则{
操作数1=弹出(堆栈和顶部);
操作数2=弹出(堆栈和顶部);
newnumber=求值(标记、操作数1、操作数2);
推送(堆栈、顶部和新编号);
ans=新编号;
}
}
令牌=strtok(空,“”);
printf(“\n当前堆栈为:\n”);
对于(i=0;i读取第一个空格的不是strtok
,而是scanf
:
scanf("%s", expression);
只要scanf
看到空格、制表符或任何其他分隔符,它就会停止读取,并将单词返回到空格处。这就是为什么使用非空分隔符时它会工作的原因
替换为fgets
,以解决问题:
fgets(expression, 100, stdin);
糟糕!谢谢!但是这会导致一个新问题:在计算最后一个表达式时,堆栈顶部会放置一个大数字。这是因为在输入最后一个数字后没有输入空格。谢谢!@user3126802您可能需要注意终止的\n
,它是fgets
字符串的一部分(它不是带有scanf
的字符串的一部分)。是的,这就是问题所在。添加\n作为分隔符,它可以工作!感谢您的帮助!请不要在回答问题后删除它。它违反了StackOverflow存在的全部理由。