【发布时间】:2015-01-15 09:23:22
【问题描述】:
我的问题陈述是接受一串数字并在屏幕上显示不同的数字。所以我尝试使用strtok() 将字符串划分为不同的数字,并使用atoi() 将这些转换为数字。但是我遇到了运行时错误。我还附上了一个示例代码。
输入
1 22 123 89 12 as a string
输出
1 22 123 89 12 as numbers
我需要对这些数字进行数学运算。所以我必须从整数转换为字符串。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main ()
{
int i,j;
char buffer [256];
char *token;
const char s[2]= " ";
fgets (buffer, 256, stdin);
token=strtok(buffer,s);
i = atoi (token);
printf("%d \n",i);
while (token!=NULL)
{token=strtok(buffer,s);
i = atoi (token);
printf("%d ",i);
}
return 0;
}
【问题讨论】:
-
atoiNULL指针上的段错误。 -
在致电
atoi之前检查token != NULL。目前您在检查 null 之前调用 atoi。