[英]atoi does not seem to be working for my program
这是一个使用堆栈的后缀计算器的简单程序,但是atoi()导致其崩溃。 为什么会这样呢? 我试过使用ch-'0'将char转换为字符串,它可以工作,但是atoi()函数将char转换为int在这种情况下似乎不起作用。
是因为ch是char还是string等。 char ch; 而不是char ch [20];
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int num[MAX],tos=-1;
push(int x)
{
if(tos==MAX)
{
printf("the stack is full");
}
else
{
printf(" l");
tos++;
num[tos]=x;
}
}
int pop()
{
if(tos<0)
{
printf("stack underflow");
}
else
return num[tos--];
}
int main()
{
char postfix[MAX],exp[MAX],ch,val;
int a,b;
printf("enter the postfix expression");
fgets(postfix,MAX,stdin);
strcpy(exp,postfix);
for(int i=0;i<strlen(postfix);i++)
{
printf(" xox ");
ch=postfix[i];
if(isdigit(ch))
{
push(ch - '0');
printf(" %d ",atoi(ch));
}
else
{
printf("%d",tos);
a=pop();
b=pop();
switch(ch)
{
case '+':
val=a+b;
break;
case '-':
val=a-b;
break;
case '*':
val=a*b;
break;
case '/':
val=a/b;
break;
}
printf("%d",val);
push(val);
}
}
printf("the result of the expression %s = %d",exp,num[0]);
return 0;
}
是因为ch是char还是string等。 char ch; 而不是char ch [20];
是。 atoi(ch)
甚至不是有效的C,并且不允许干净地编译。
在这种情况下,您可以基于ch
和空终止符创建一个临时字符串。 例如,通过复合文字: (char[2]){ch, '\\0'}
。
而且,永远不要将atoi
用于任何目的,因为它的错误处理能力很差,并且是完全多余的功能。 请改用strtol
系列功能。
您可以这样调用strtol
:
strtol( (char[2]){ch, '\0'}, // string to convert from
NULL, // end pointer, not used, set to NULL
10 ); // base 10 = decimal
例:
printf(" %d ", (int)strtol( (char[2]){ch, '\0'}, NULL, 10) );
这完全等同于更具可读性的代码:
char tmp[2] = { ch, '\0' };
int result = (int) strtol(tmp, NULL, 10);
printf(" %d ", result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.