strstr()函数 [英] strstr() function
问题描述
我正在尝试编写一个程序,将用户输入的子字符串与字符串数组进行比较.
I am trying to write a program that compares a substring that the user enters with an array of strings.
#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;
}
例如,当我输入青蛙时,它应该打印青蛙怪胎"消息,但什么也不会输出.
When I enter frogs, for example it should print the message "frogs are freaky", but it prints out nothing.
因此,我尝试写一行以每次打印出strstr()函数的值,并且它们都返回0,这意味着所有比较都失败了.我不明白为什么,有人可以帮我吗?
So I tried to write a line to print out the value of the strstr() function each time and they all returned 0, which means all the comparisons failed. I don't understand why, can someone help me please?
推荐答案
这是因为您的字符串包含换行符.
This is because your string contains the newline character.
从 fgets
文档:
换行符使fget停止读取,但是该函数将其视为有效字符并包含在复制到str的字符串中.
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
这应该可以解决问题(演示):
This should fix the problem (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;
}
这篇关于strstr()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!