gpt4 book ai didi

c - strstr() 不适用于 C

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:12 25 4
gpt4 key购买 nike

我有下面的代码。问题是当我运行它时,它没有显示我提示的搜索;在 for 中尝试 printf("%s", strstr(tracks[i], search_for)) 返回 null,但是对 tracks 做同样的事情没有问题[i]search_for。请帮忙!

#include <stdio.h>
#include <string.h>

char tracks[][80]={
"I left my heart in Harvard Med Scholl",
"Newark, Newark - a wonderful town",
"Dancing with a Dork",
"From here to maternity",
"The girl from Iwo Jima",
};

void find_track(char search_for[]){
int i;
for(i=0; i<5; i++){
if(strstr(tracks[i], search_for)){
printf("Track %i: '%s'\n", i, tracks[i]);
}
}
};

int main(){

char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}

最佳答案

正如我们在 fgets() 中看到的那样文档,如果行末有换行符,它将包含在生成的字符串中:

Reads at most count - 1 characters from the given file stream and stores them in str. The produced character string is always NULL-terminated. Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

所以在这种情况下,如果我们输入 "Newark",那么我们有:

search_for[] = {'N', 'e', 'w', 'a', 'r', 'k', '\n', '\0', ...};

您需要删除多余的换行符。

关于c - strstr() 不适用于 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26287060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com