简体   繁体   中英

Why does my C program not print output from an if statement?

This program ought to output two variables which are in an if statement. However it does not but anything printed outside does.

#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 search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    find_track(search_for);
    return 0;
}

I expected it to output to show the track number and the associated string but it does not.

The fgets function will read a line of text up to a newline, and it will read and store the newline if there is space for it. So if for example you enter "here" then search_for will contain "here\\n" . None of your strings contain a newline so you never find anything.

You'll need to strip the newline from the string that you read in:

search_for[strcspn(search_for,"\n")]=0; 

The strcspn function returns the number of characters from the start of the string which are not in the given list. So if your string contains a newline it will return the index of the newline, otherwise it contains the index of the terminating null byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM