strcmp on a line read with fgets

后端 未结 6 1108
你的背包
你的背包 2020-11-22 11:56

I\'m trying to compare two strings. One stored in a file, the other retrieved from the user (stdin).

Here is a sample program:

int main()
{
    char          


        
6条回答
  •  名媛妹妹
    2020-11-22 12:15

    The fgets is appending a \n to the string that you are pulling in from the user when they hit Enter. You can get around this by using strcspn or just adding \n onto the end of your string you're trying to compare.

    printf("Please enter put FILE_NAME (foo1, 2, or 3), ls, or exit: \n");
    fgets(temp, 8, stdin);
    temp[strcspn(temp, "\n")] = '\0';
    if(strcmp(temp, "ls") == 0 || strcmp(temp, "exit") == 0)
    

    This just replaces the \n with a \0, but if you want to be lazy you can just do this:

    printf("Please enter put FILE_NAME (foo1, 2, or 3), ls, or exit: \n");
    fgets(temp, 8, stdin);
    if(strcmp(temp, "ls\n") == 0 || strcmp(temp, "exit\n") == 0)
    

    But it's not as elegant.

提交回复
热议问题