使用 fgets 读取的行上的 strcmp [英] strcmp on a line read with fgets
问题描述
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?
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|
| |
+-+-+-+--+--+
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, "
")] = ' ';
+-+-+-+--+
|b|o|b| |
+-+-+-+--+
Now, strcmp
should return 0...
这篇关于使用 fgets 读取的行上的 strcmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!