strcmp on a line read with fgets

后端 未结 6 1195
你的背包
你的背包 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:21

    strcmp is one of the few functions that has the reverse results of true and false...if the strings are equal, the result is 0, not 1 as you would think....

    if (strcmp(a, b)) {
        /* Do something here as the strings are not equal */
    } else {
        /* Strings are equal */
    }
    

    Speaking of fgets, there is a likelihood that there is a newline attached to the end of the string...you need to get rid of it...

    +-+-+-+--+--+
    |b|o|b|\n|\0|
    +-+-+-+--+--+
    

    To get rid of the newline do this. CAVEATS: Do not use "strlen(aName) - 1", because a line returned by fgets may start with the NUL character - thus the index into the buffer becomes -1:

    aName[strcspn(aName, "\n")] = '\0';
    
    +-+-+-+--+
    |b|o|b|\0|
    +-+-+-+--+
    

    Now, strcmp should return 0...

提交回复
热议问题