我的問題陳述是接受一串數字並在屏幕上顯示不同的數字。所以我試着用strtok()
將字符串分成不同的數字,然後用atoi()
將這些數字轉換成數字。但我得到運行時錯誤..我還附上了一個示例代碼。在C中使用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;
}
'atoi'段錯誤'NULL'指針。 –
在調用atoi之前檢查'token!= NULL'。目前你在檢查null之前調用atoi。 –