简体   繁体   中英

C-Programming.Why Doesn't This Work?

The following program should search over a multi-dimensional array. When I enter the word town as input, it should return Track 1: Newark,Newark-A Wonderful Town but I don't receive any output (nothing happens), any ideas how to fix it?

I'm working on the Head First C book.

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

/* Run this program using the console pauser
or add your own _getch, system("pause") or input loop */

char tracks[][80]={
        "I Left My Heart In Harvard Med School",
        "Newark,Newark-A Wonderful Town",
        "From Here to Maternity",
        "The Girl From Iwo Jima",
    };


void find_track(char search_for[]){
    int i;
    for (i=0;i<=4;i++){
        if(strstr(tracks[i],search_for)){

            printf("Track %i:'%s' \n",i,tracks[i]);

    }
    }
}

int main(int argc, char *argv[]) {
    char search_for[80];
    printf("Search for: ");
    fgets(search_for,80,stdin);
    find_track(search_for);

    return 0;
}

As pointed out above, fgets stores the newline from your input, and it will not match. Chopping the last character off that search_for string will make it work, as long as you match the case of the test in the title. Also, note that your for loop should have i < 4 instead of i <= 4 .

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
char tracks[][80]={
        "I Left My Heart In Harvard Med School",
        "Newark,Newark-A Wonderful Town",
        "From Here to Maternity",
        "The Girl From Iwo Jima",
    };


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

int main(int argc, char *argv[]) {
    char search_for[80];
    printf("Search for: ");
    fgets(search_for,80,stdin);
    search_for[strlen(search_for)-1] = '\0'; // truncate input
    find_track(search_for);

    return 0;
}

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