I have this piece of code. When I run it, it returns 13, -13, and 0.
Isn’t it supposed to return 1 if the str1 is greater than str2 and -1 if str1 is less than str2.
I get 13, -13 and 0.
#include <iostream>
#include <string>
#include <cstring>
int main() {
char str1[] = "Megadeth";
char str2[] = "Metallica";
// Should return -1 because "Megadeth" < "Metallica" lexicographically
int result = strcmp(str1, str2);
std::cout << "Comparing " << str1 << " and " << str2 << ": " << result << std::endl;
// Should return 1 because "Metallica" > "Megadeth" lexicographically
result = strcmp(str2, str1);
std::cout << "Comparing " << str2 << " and " << str1 << ": " << result << std::endl;
// Should return 0 because "Megadeth" = "Megadeth" lexicographically
result = strcmp(str1, str1);
std::cout << "Comparing " << str1 << " and " << str1 << ": " << result << std::endl;
return 0;
}
Here is the result:
Comparing Megadeth and Metallica: -13
Comparing Metallica and Megadeth: 13
Comparing Megadeth and Megadeth: 0
I’ve just followed a tutorial on the Internet and they say it’s supposed to return ones. I don’t know what is causing this.
>Solution :
strcmp is not defined to return 1, 0, or -1. The result is either positive if the first is lexicographically greater than the second, negative if the first is lexicographically less than the second, or 0 otherwise. Only the sign, or 0, are defined, not the magnitude.
man strcmp:
The
strcmp()andstrncmp()functions return an integer greater than, equal to, or less than 0, according as the string s1 is greater than, equal to, or less than the string s2. The comparison is done using unsigned characters, so that ‘\200′ is greater than `\0’.
Letters that come first, at least on your implementation, are considered ‘smaller.’ So the first letter to mismatch between Megadeth and Metallica is the g versus the t. t is greater than g so when Metallica is second, the result is negative.