For unknown reason, result of running my C program is quite unexpected. I think that it has to be some kind of a beginner mistake, however I can't find out really, where is it.
#include <stdio.h>
#include <string.h>
int main()
{
char string1[50];
char string2[50];
int compare;
puts("Enter two strings: ");
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);
compare=strcmp(string1, string2); /* usage of extra variable makes the code more readable but wastes more memory */
printf("%d: ",compare);
if (compare<0) puts("First string is lesser");
else if (compare>0) puts ("First string is bigger");
else puts("Strings are equal");
return 0;
}
And on testing:
Enter two strings:
heheisntthisalongstring
heheisntthisalongstring
1: First string is bigger
------------------
(program exited with code: 0)
Press return to continue
Shouldn't those strings be equal?
fgets(s, num, stream)
reads characters until (num-1) characters have been read or either a newline or the End-of-File is reached, whichever comes first. When initializing your strings with all 0strlen
returns 0 andfgets
has no characters to read. – Dilorenzo