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?
fgets
appends the newline to the string, so you'll end up withbob\n\0
which isn't the same asbob\0
.Mostly because of the end of line char in the input "\n" under unix like system.
Because fgets is embededing the newline character into the variable
targetName
. This is throwing off the comparison.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 usingstrcspn
or just adding\n
onto the end of your string you're trying to compare.This just replaces the
\n
with a\0
, but if you want to be lazy you can just do this:But it's not as elegant.
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....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...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:
Now,
strcmp
should return 0...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)You need to remove the newline from the end of targetName before you compare.
or add the newline to your test string.