How do I properly compare strings in C?
Ok a few things: gets
is unsafe and should be replaced with fgets(input, sizeof(input), stdin)
so that you don't get a buffer overflow.
Next, to compare strings, you must use strcmp
, where a return value of 0 indicates that the two strings match. Using the equality operators (ie. !=
) compares the address of the two strings, as opposed to the individual char
s inside them.
And also note that, while in this example it won't cause a problem, fgets
stores the newline character, '\n'
in the buffers also; gets()
does not. If you compared the user input from fgets()
to a string literal such as "abc"
it would never match (unless the buffer was too small so that the '\n'
wouldn't fit in it).
Use strcmp
.
This is in string.h
library, and is very popular. strcmp
return 0 if the strings are equal. See this for an better explanation of what strcmp
returns.
Basically, you have to do:
while (strcmp(check,input) != 0)
or
while (!strcmp(check,input))
or
while (strcmp(check,input))
You can check this, a tutorial on strcmp
.