每次我尝试使用 strtok() 时,我都会遇到段错误。不知道为什么-我是 C 的新手。
这是我的代码:
#include "shellutils.h"
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
char input[150];
while(1) {
prompt();
fgets(input, 150, stdin);
char *fst_tkn = strtok(input, " ");
printf("%s", fst_tkn);
if(feof(stdin) != 0 || input == NULL) {
printf("Auf Bald!\n");
exit(3);
}
}
}
感谢您的帮助!
最佳答案
关于代码:
char *fst_tkn = strtok(input, " ");
printf("%s", fst_tkn);
如果您的 input
变量为空,或仅包含空格,则 fst_tkn
将设置为 NULL
。然后,当您尝试将其打印为字符串时,所有的赌注都没有了。
您可以通过调整给 input
的值在以下代码中看到:
#include <stdio.h>
#include <string.h>
int main (void) {
char input[] = "";
char *fst_tkn = strtok (input, " ");
printf ("fst_tkn is %s\n", (fst_tkn == NULL) ? "<<null>>" : fst_tkn);
return 0;
}
关于c - c 中的 strtok() - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554102/