gpt4 book ai didi

c - atoi 似乎不适用于我的程序

转载 作者:太空宇宙 更新时间:2023-11-04 07:50:12 24 4
gpt4 key购买 nike

这是一个使用堆栈的后缀计算器的简单程序,但是 atoi() 导致它崩溃。为什么会这样?我已经尝试使用 ch-'0' 将 char 转换为字符串并且它有效,但是在这种情况下用于 char 到 int 转换的 atoi() 函数似乎不起作用。

是因为ch不是char也不是string例如。炭黑;而不是 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;
}

最佳答案

Is it because ch is a char nor string eg. char ch; and not 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);

关于c - atoi 似乎不适用于我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54330130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com