Ace*_*Ace 0 c arrays printf binary-search
我注意到我的变量input2只打印字符串中的第一个单词,这导致程序其余部分出现问题(即不能正确打印名词).任何关于为什么会发生这种情况的见解将不胜感激
int main(int argc, char* argv[]){
char *input = strtok(argv[1], " \"\n");
//printf("%s\n", input);
int position;
int check = 0;
int first = 1;
while (input != NULL) {
position = binary_search(verbs, VERBS, input);
//printf("%s\n", input);
//printf("%d\n", position);
if (position != -1){
if (first){
printf("The verbs were:");
first = 0;
check = 1;
}
printf(" %s", input);
}
input = strtok(NULL, " ");
}
if (check == 1){
printf(".\n");
}
if (check == 0){
printf("There were no verbs!\n");
}
char *input2 = strtok(argv[1], " \"\n");
//printf("%s\n", input2);
int position2;
int check2 = 0;
int first2 = 1;
while (input2 != NULL) {
position2 = binary_search(nouns, NOUNS, input2);
//printf("%s\n", input2);
//printf("%d\n", position2);
if (position2 != -1){
if (first2){
printf("The nouns were:");
first2 = 0;
check2 = 1;
}
printf(" %s", input2);
}
input2 = strtok(NULL, " ");
}
if (check2 == 1){
printf(".\n");
}
if (check2 == 0){
printf("There were no nouns!\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
strtok()修改你在传递为源,所以调用字符串strtok()与argv[1]第二次对原值不采取行动argv[1],但只有第一个令牌.
您可能想要执行以下操作:
char* s = strdup(argv[1]);
Run Code Online (Sandbox Code Playgroud)
并且对字符串so的操作argv[1]将保持不变 - 您可以稍后再次处理它.但是,完成后,您需要释放重复的字符串的内存.