+ 2
C++ - Why is output 5?
#include <iostream> #include <string> using namespace std; int main() { string s1("hi sololearn"); string s2("hi solo"); cout << s1.compare(s2); return 0; }
1 Answer
+ 6
The return value of compare() indicates the relationship between the two strings. It might be a bit confusing, but a return value of 0 (which is boolean false, heh) means the strings match exactly.
The exact return table can be seen in the reference:
http://www.cplusplus.com/reference/string/string/compare/
https://en.cppreference.com/w/cpp/string/basic_string/compare
In this case, the output is five because all characters that are compared actually match, but the compared string 's1' is five characters longer than the comparing string 's2'.