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
. Usestrncmp
instead, especially if you are comparing against a fixed-width string. Usingstrncmp(aName,targetName,strlen(aName))
should work for you here. – Waiststrcmp
will continue comparing until a NULL-terminator is reached or the strings differ. If you cannot be certain that your strings will always be properly NULL-terminated,strcmp
can introduce buffer overflows and memory access violations.strncmp
isn't just for reading prefixes; set the final parameter to the size of your fixed-length buffer to ensure that you aren't overflowing your array bounds. – Waiststrlen
to compute the size argument tostrncmp
. Doing so adds no additional protection thatstrcmp
does not already have. Using a fixed size value, such as the buffer size as your second comment indicates, is whenstrncmp
should be used. – Prodrome