Alex Rivera | Logout

strcmp on a line read with fgets

Asked 2010-03-08T21:13:44.767
10

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 targetName[50];
    fgets(targetName,50,stdin);

    char aName[] = "bob";
    printf("%d",strcmp(aName,targetName));

    return 0;
}

In this program, strcmp returns a value of -1 when the input is "bob". Why is this? I thought they should be equal. How can I get it so that they are?

Edit
Report

1 Answer

1

fgets appends the newline to the string, so you'll end up with bob\n\0 which isn't the same as bob\0.

answered 2010-03-08T21:18:12.883

Your Answer