我是 C 的新手,我想学习一些困扰我的东西。
我有一个代码,我使用了 strtok,基本上它得到一个带有 _#_
的字符串,并将它从字符串中分离出来,剩下的变成字符和整数(我为此使用了 atoi)
当我输入类似这样的内容时程序运行良好:hello_#_2001_#_name_#_HARRY
它返回 hello,2001,name 和 HARRY。但是,当我仅输入 hello_#_ 时,它会继续运行,但会停止执行任何操作。我想我需要为第一个 NULL 分配一个特定的指针,但不确定我的想法是否正确,你能帮忙吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *split(char words[99])
{
int i;
char *word=strtok(words, "_#_");
char *year=strtok(NULL, "_#_");; // assigning NULL for previousely where it left off
char *definition=strtok(NULL,"_#_");
char *synonyms=strtok(NULL,"_#_");
i=atoi(year);
printf("%s\n", word);
printf("%i\n",i);
printf("%s\n", definition);
printf("%s\n", synonyms);
return 0;
}
int main()
{
char words[100];
printf("Enter a string\n");
scanf("%s", words);
split(words);
}
最佳答案
当我运行您的程序并输入字符串 hello_#_
时,它会在调用 atoi
时抛出段错误。这是预期的,因为 year
、definition
和 synonyms
都将为 NULL
。因此,在调用 atoi
之前,您应该检查 year
的 NULL
值。
关于使用 strtok() 后的条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20903099/