首页 > 解决方案 > atoi 似乎不适用于我的程序

问题描述

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

是不是因为 ch 是 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;
}

标签: cerror-handlingcharatoi

解决方案


是不是因为 ch 是 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);

推荐阅读