strtok(NULL,)分段错误

时间:2013-12-02 17:00:29

标签: c segmentation-fault strtok

输入一段代码是:

initfs /home/bin/usr/a.txt 1000 100

代码如下:

printf("Enter a command\n");
scanf("%99[0-9a-zA-Z ]s", userInput);
printf("%s\n", userInput);
command = strtok(userInput, " ");
filePath = strtok(NULL, " ");

userInput中,存储了"initfs /home/bin/usr/a.txt 1000 100"并且 在变量command中,存储了"initfs"。 但是,如果我打印filePath,它会给出分段错误。 它应该打印"/home/bin/usr/a.txt"

可能是什么问题?

1 个答案:

答案 0 :(得分:1)

一般来说,为了解析键盘输入,我发现用fgets(或getline读取整行文本,如果你愿意),然后解析它就不那么令人头疼了它从那里。 e.g:

char userInput[1024];
while (fgets(userInput, 1024, stdin) != NULL) {
    handleInput(userInput);
}

...
void handleInput(char *userInput)
{
    char *command, *filePath;
    command = strtok(userInput, " ");
    filePath = strtok(NULL, " ");
    ...
}

直接在用户输入上使用scanf太过于挑剔,并且很容易对输入数据的微小变化感到困惑。