所以我有以下代码:
//Get the line
fgets(line,MAX,stdin);
//Remove trailing new line character
line[strcspn(line,"\r\n")] = 0;
//Count number of tokens
int tokenCounter = 1;
for (int i = 0; i < strlen(line); i++){
if (line[i] == ' '){
tokenCounter++;
}
}if (tokenCounter >= 3){
command = strtok(line," ");
id = strtok(NULL," ");
name = strtok(NULL," ");
if (tokenCounter > 3){
for (char *p = strtok(NULL," "); p != NULL; p = strtok(NULL," ")){
strcat(name,p);
}
}
printf("Command: %s -- ID: %s -- Name: %s\n",command,id,name);
}
该代码应该执行的操作是将行中的第一个单词保存在“ command”变量中,将行中的第二个单词保存在“ id”变量中,并将其余单词保存在一个单词中变量称为“名称”。但目前其无法正常工作。其工作原理如下:
Input > word1 word2 word3
Output > Command: word1 -- ID: word2 -- Name: word3
Input > word1 word2 word3 word4
Output > Illegal Instruction: 4
正确的输出应该如下:
Input > word1 word2 word3
Output > Command: word1 -- ID: word2 -- Name: word3
Input > word1 word2 word3 word4
Output > Command: word1 -- ID: word2 -- Name: word3 word 4
我在循环中做错什么了吗?如果是,可以更改什么?