c - 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;
}
解决方案
是不是因为 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);
推荐阅读
- c# - “请求被中止:无法在 HttpWebRequest 中创建 SSL/TLS 安全通道”,即使在指定 ServicePointManager.SecurityProtocol 之后也是如此
- json - 限制空数据导致 JPA 中的映射
- xml - XSLT for-each 循环转换
- angular - Validators.nullValidator(control: AbstractControl) 的意义何在?
- ios - 如何将负零与正零分开?
- dialogflow-es - 使用 google mini 设备进行测试时无法获取设备粗略位置
- android - “原生平台”在上传到 Play 商店时减少,并警告说“应用程序可用于在更少类型的设备上进行新安装”
- node.js - Angular 6 - 服务器未运行时未检测到现有文件的更改
- python - 从文件中提取存储的用户名和密码并通过python脚本使用它的有效方法是什么?
- javascript - 将组件更改为在 reactJS 中的功能