Strcmp () considers the lines arent equal .. but are they?

For some unknown reason, the result of running my C program is quite unexpected. I think this should be some kind of newbie, but I can’t understand where she is.

#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 when testing:

Enter two strings: 
heheisntthisalongstring
heheisntthisalongstring
1: First string is bigger


------------------
(program exited with code: 0)
Press return to continue

Shouldn't these lines be equal?

+5
source share
4 answers
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);

It is not right. string1and are string2not initialized, but strlensimply counts the number of bytes until it reaches \0. In this case, strlencan return any (random non-negative) number.

Use sizeofinstead strlenhere.

+13
source

Here

 char string1[50]; 
 char string2[50]; 

, strlen , char, . , - .

+3

string1 memset 0, strlen(string1) (50). strlen \0. , ( undefined).

memset string1, string2, .

char string1[50] = {0}; 
char string2[50] = {0};

sizeof 50.

fgets(string1, sizeof(string1), stdin); 
fgets(string2, sizeof(string2), stdin);

scanf

scanf("%s", string1);
scanf("%s", string2);
0

this-strlen

Although the code you use is not very good, but you can get the expected response using strncmp, specifying the third parameter of a strlencommon string variable. Just for fun. Always initialize your variables or they may cause your application to crash. You can see examples here- strncmp

0
source

All Articles