C编程。为什么不工作?

问题描述 投票:-1回答:1

以下程序应搜索多维数组。当我输入单词town作为输入时,它应该返回Track 1: Newark,Newark-A Wonderful Town但我没有收到任何输出(没有任何反应),任何想法如何解决它?

我正在研究Head First C的书。

#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;
}
c multidimensional-array
1个回答
2
投票

如上所述,fgets会根据您的输入存储换行符,但不会匹配。只要你匹配标题中测试的情况,从search_for字符串中删除最后一个字符将使其工作。另外,请注意你的for循环应该有i < 4而不是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;
}
© www.soinside.com 2019 - 2024. All rights reserved.