In the code below I use strcmp to compare two strings and make this comparison the condition of an if statement.
With the code below, the output will be hello world
, because string "one" is equal to 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 string are different so I change the program that 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 dont understand the reason why it does not print out anything.
Because strcmp()
will return a negative integer in this case.
So change this:
if (strcmp(one, two) == 1) {
to this:
if (strcmp(one, two) != 0) {
to take into account all the cases that the strings differ.
Notice that you could have spotted that yourself by either reading the ref or by printing what the functions returns, like this:
printf("%d\n", strcmp(one, two));
// prints -23
According to the C Standard (7.23.4.2 The strcmp function)
3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.
So what you need is to write the if statement like
if ( strcmp(one, two) != 0 ) {
or
if ( !( strcmp(one, two) == 0 ) ) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With