strcmp on a line read with fgets

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

    fgets reads until it sees a newline then returns, so when you type bob, in the console, targetName contains "bob\n" which doesn't match "bob". From the fgets documenation: (bolding added)

    Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first. A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str. A null character is automatically appended in str after the characters read to signal the end of the C string.

    You need to remove the newline from the end of targetName before you compare.

    int cch = strlen(targetName);
    if (cch > 1 && targetName[cch-1] == '\n')
       targetName[cch-1] = '\0';
    

    or add the newline to your test string.

    char targetName[50];
    fgets(targetName,50,stdin);
    
    char aName[] = "bob\n";
    printf("%d",strcmp(aName,targetName));
    

提交回复
热议问题