C Code for String matching[Head First C] doesn't seem to work

后端 未结 2 896
礼貌的吻别
礼貌的吻别 2020-12-21 05:39
#include 
#include 

char tracks[][80] = {
\"I left my heart in Harvard Med School\",
\"Newark, Newark - a wonderful town\",
\"Dancing         


        
相关标签:
2条回答
  • 2020-12-21 06:31

    As already pointed out by @cnicutar, fgets leaves the newline char (code 10) in the string. You can find this out by yourself by iterating over the char array and printing the character codes and looking the special chars up in an ASCII code table (http://www.asciitable.com/):

    int main()
    {
        int i;
        char search_for[80];
        printf("Search for: ");
        fgets(search_for, 80, stdin);
        scanf("%79s", search_for);
    
        // print index, char code, char itself
        for (i=0;i<80;i++) {
            printf("%d: %d %c\n", i, search_for[i], search_for[i]);
        }
        find_track(search_for);
        getch();
    
        return 0;
    }
    

    The output will be:

    ...
    0: 116 t
    1: 111 o
    2: 119 w
    3: 110 n
    4: 10
    5: 0 
    ...
    

    You can use the function "scanf" and limit the number of read chars to 79 (1 char reserve for NULL char at the end of the string as the buffer holds max 80 chars). See: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/ for reference.

    int main()
    {
        char search_for[80];
    
        printf("Search for: ");
        scanf("%79s", search_for);
    
        find_track(search_for);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-21 06:37

    The problem with the code above is that it doesn't account for the fact that fgets leaves the newline in the string. So when you type town and hit enter, you'll end up searching for "town\n".

    A cheap way to solve this would be to fix the string after calling fgets

    search_for[strlen(search_for) - 1] = 0;
    
    0 讨论(0)
提交回复
热议问题