C - strcmp associated with if statement

In the code below, I use strcmp to compare two strings and make this comparison a condition of the if statement. With the code below, the output will be hello world , because the string "one" is equal to the string "two".

 #include <stdio.h> #include <string.h> char one[4] = "abc"; char two[4] = "abc"; int main() { if (strcmp(one, two) == 0) { printf("hello world\n"); } } 

Now I want to change the program and make it print hello world if the two lines are different, so I change the program this way:

 #include <stdio.h> #include <string.h> char one[4] = "abc"; char two[4] = "xyz"; int main() { if (strcmp(one, two) == 1) { printf("hello world\n"); } } 

I don’t understand why it doesn’t print anything.

+5
source share
5 answers

Since strcmp() returns a negative integer in this case.

So change this:

 if (strcmp(one, two) == 1) { 

:

 if (strcmp(one, two) != 0) { 

to take into account all cases where the lines are different.

Note that you could notice this yourself, either by reading ref, or by printing functions returns, for example:

 printf("%d\n", strcmp(one, two)); // prints -23 
+6
source

strcmp returns zero when both lines are equal, it returns something other than zero when they are different, so you need to change your if code in the code to something like this

 if ( strcmp(one, two) != 0 ) { printf("hello world\n"); } 
+2
source

According to the C standard (7.23.4.2 strcmp function)

3 The strcmp function returns an integer greater than, equal to, or less than zero , respectively, since the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

So you need to write an if statement, for example

 if ( strcmp(one, two) != 0 ) { 

or

 if ( !( strcmp(one, two) == 0 ) ) { 
+2
source

You misunderstood how strcmp works. To check if strings are used, use

 if(strcmp(one, two)) 
+1
source

The correct behavior:

 if (strcmp(one, two) != 0) { printf("hello world\n"); } 

Actually this function returns the difference between two lines:

  • <0: the first character that does not match has a lower value in ptr1 than in ptr2.
  • 0: the contents of both lines are equal
  • > 0: the first character that does not match has a larger value in ptr1 than in ptr2.

This is an example of how strcmp can be implemented.

+1
source

Source: https://habr.com/ru/post/1265980/


All Articles