【发布时间】:2014-07-19 01:47:15
【问题描述】:
我正在编写 C 编程书籍中的这个示例,strstr 命令应该在值为 true 时触发 printf 命令。它试图在曲目中找到一个字符串并返回它是在哪个曲目中找到的。我已经为此玩了一个多小时,似乎无法找到问题所在。目前,即使应该匹配,它也不会打印任何内容。
#include <stdio.h>
#include <string.h>
char tracks[][80] = {
"Boston",
"Where the Streets Have No Name",
"Row Row Row your Boat",
"Gangsta Paradise",
"Yoda",
};
void findTrack(char searchFor[]){
int i;
for(i = 0; i < 5; i++){
if(strstr(tracks[i], searchFor))
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
int main(){
char searchFor[80];
printf("what is your string?: ");
fgets(searchFor, 80, stdin);
printf("searching for: %s", searchFor);
findTrack(searchFor);
return 0;
}
【问题讨论】:
-
strstr不返回真或假。它返回一个指针。 -
printf("searching for: %s", searchFor);这有效吗?输出是什么? -
您需要从
searchFor中删除行尾的换行符('\n')。 -
@chris 你是在争论迂腐的语义还是你只是不知道你在说什么?非空值在 C 中为真;如果在字符串中找到子字符串,strstr 将返回非 NULL,因此返回 true,因此将满足
if条件。 -
@JimBalter,我知道用法是完全正确的。我的整个论点都是基于当值为真时。 "value" 似乎最适合
strstr的结果,所以 "true" 不合适,这表明我可能对strstr返回的类型缺乏理解。很容易找到如何使用函数并从中错误推断事物的示例。