As others have said, you can't compare strings with ==
. In order for your code to work, you need to strip the \n
character appended from fgets()
. Otherwise you are comparing:
if (strcmp("mother\n", "mother") == 0) {
Which will always be false, unless you remove the \n
character.
Since fgets()
returns NULL
if unsuccessful when reading input from the user, it is also safe to check that, like this:
if (fgets(string, 20, stdin) == NULL) {
/* Exit program */
}
You can also add some extra error checking for fgets()
, such as checking for buffer overflow, which can be checked like this:
slen = strlen(string);
if (slen > 0) {
if (string[slen-1] == '\n') {
string[slen-1] = '\0';
} else {
/* Exit program */
}
}
After these considerations, your code can possibly look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 20
int
main(int argc, char *argv[]) {
char string[BUFFSIZE];
size_t slen;
const char *compare = "mother";
printf("Enter a string: ");
if (fgets(string, BUFFSIZE, stdin) == NULL) {
printf("Error reading string into buffer.\n");
exit(EXIT_FAILURE);
}
slen = strlen(string);
if (slen > 0) {
if (string[slen-1] == '\n') {
string[slen-1] = '\0';
} else {
printf("Buffer overflow. Exceeded buffer size of %d.\n", BUFFSIZE);
exit(EXIT_FAILURE);
}
}
if (!*string) {
printf("No string entered.\n");
exit(EXIT_FAILURE);
}
printf("My string = %s.\n", string);
if (strcmp(string, compare) == 0) {
printf("They are the same.\n");
} else {
printf("They are not the same.\n");
}
return 0;
}