I am using strcmp
to compare two strings. lhs
is coming from a filestream via fgets
. rhs
is being created generated by a for loop to be a sequence of n-1
whitespaces.
#include <string.h>
#include <stdio.h>
int main() {
size_t n = 10;
char rhs[n];
memset(rhs, ' ', n - 1); // Fill with spaces using memset()
rhs[n-1] = 0; // Add NUL terminator
printf("len=%zu\n", strlen(rhs));
char lhs[n];
FILE* file = fopen("test", "r");
fgets(lhs, sizeof(lhs), file);
printf("read=%s\n", lhs);
return 0;
}
print
for this):
lhs
= " "
rhs
= " "
Yet, strcmp(lhs, rhs) != 0
. This should return a 0
indicating that the strings are identical, but instead I get some other non-zero value.
Why aren't these strings considered equal?
Cleaned up this code to create a complete, minimal example looks like this:
#include <string.h>
#include <stdio.h>
int main() {
size_t n = 10;
char rhs[n];
memset(rhs, ' ', n - 1); // Fill with spaces using memset()
rhs[n-1] = 0; // Add NUL terminator
printf("len=%zu\n", strlen(rhs));
char lhs[n];
FILE* file = fopen("test", "r");
fgets(lhs, sizeof(lhs), file);
printf("read=%s\n", lhs);
return 0;
}
Where here it's important to not assign from fgets
, that's a warning if you have -Wall
turned on.