strstr 未返回所需结果

strstr not returning desired result

你能找出这段代码中的错误吗,它无法打印这首歌,即使我传递了有效的参数来查找

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

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "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 askedSong[80];
    printf("%s", "Hey buddy, what is the good one today? ");
    fgets(askedSong, sizeof(askedSong), stdin);
    find_track(askedSong);
    return 0;
}
  1. 假设你可以在fgets之后得到最后的"\n"。需要 trim 它(如果你从键盘输入)。您可以尝试 运行 使用文件输入: yourexefile.exe < input.txt > output.txt 并发现它以某种方式工作
  2. 假设你应该在循环中找到结果后中断。

这里的问题是 fgetsaskedSong 中包含尾随的换行符 '\n'

这是我找到它的方式 --- 我 运行 调试器中的程序并在 find_track() 中放置了一个断点。然后当出现提示时,我在命令行中输入“girl”,看到函数的参数是“girl\n”。

这是我在调试器中看到的:

Hey buddy, what is the good one today? girl

Breakpoint 1, find_track (search_for=0x7fffffffd9c0 "girl\n") at test.c:15
15      for(i = 0; i < 5; i++) {
(gdb) 

C 中的 '\n' trim 有很多古怪的方法:Removing trailing newline character from fgets() input

fgets extra \n (enter) 有问题

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

char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "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)!=NULL) {
            printf("Track %i: '%s'\n", i, tracks[i]);
        }
    }
}

int main() {
    char askedSong[80];
    printf("%s", "Hey buddy, what is the good one today? ");
    scanf("%s",askedSong);// try to use scanf to ovoid \n in the buffer
    find_track(askedSong);
    return 0;
}

fgets 在字符串中保留换行符。轻松修复:

fgets(askedSong, sizeof(askedSong), stdin);
askedSong[strcspn(askedSong, "\n")] = 0;