我正在尝试编写一个程序,将用户输入的子字符串与字符串数组进行比较。
#include <stdio.h>
#include <string.h>
char animals[][20] = {
"dogs are cool",
"frogs are freaky",
"monkeys are crazy"
};
int main() {
char input[10];
puts("Enter animal name: ");
fgets(input, sizeof(input), stdin);
int i;
for(i = 0; i < 3; i++) {
if(strstr(animals[i], input))
printf("%s", animals[i]);
}
return 0;
}例如,当我输入frogs时,它应该打印消息"frogs are freaky",但它什么也不打印。
因此,我尝试编写一行代码,每次输出strstr()函数的值,它们都返回0,这意味着所有的比较都失败了。我不明白为什么,有人能帮帮我吗?
发布于 2013-06-04 05:01:27
这是因为您的字符串包含换行符。
从fgets documentation
换行符使fgets停止读取,但它被函数视为有效字符,并包含在复制到str的字符串中。
这应该可以解决问题(demo):
#include <stdio.h>
#include <string.h>
char animals[][20] = {
"dogs are cool",
"frogs are freaky",
"monkeys are crazy"
};
int main() {
char input[10];
printf("Enter animal name: ");
scanf("%9s", input);
int i;
for(i = 0; i < 3; i++) {
if(strstr(animals[i], input))
printf("%s", animals[i]);
}
return 0;
}发布于 2013-06-04 05:01:02
fgets在缓冲区中包含输入的换行符。您的字符串中没有换行符,因此它们永远不会匹配。
发布于 2013-06-04 05:01:06
最有可能的是,fgets()包含用户按Enter时输入的换行符。删除它:
char *p = strchr(input, '\n');
if (p)
*p = 0;https://stackoverflow.com/questions/16905728
复制相似问题