How to Compare 2 strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to Compare 2 strings

I wrote the following lines to compare which string is the greater _________________________________ #include <iostream> using namespace std; int main() { if ("c" > "b") cout << "hi"; return 0; } ____________________ It should execute the if body , but it doesn't, can any one explain this situation?

8th Dec 2020, 9:26 PM
Sulaiman Saleh Alzyoud
Sulaiman Saleh Alzyoud - avatar
4 Answers
+ 2
It's not working as expected. Actually you can't do it on strings.. I confused on getting result on using '<'. But it lead wrong way.. It can say only equal or not. For determine which is greater, we have function to do that in string class.. In c, <cstring> file have strcmp function. Use that. if(strcmp( "c", "b") > 0) cout <<"hi" ; I may think about it again.. If I found better solution, I update here.. I updated previous 1 already.. Look again..
8th Dec 2020, 10:00 PM
Jayakrishna 🇮🇳
+ 3
You can't compare strings like that. Instead use cstring strcmp function to compare strings.. It return if 1st string greater then return positive value, if less then return Negetive value, returns zero(0) if both are equal.
8th Dec 2020, 9:44 PM
Jayakrishna 🇮🇳
+ 1
Using directly string literals in comparison will result unexpected behaviours. So don't use string literals in comparisons.. First save in variables and use in comparisons.. string s1= "c", s2="b" ; if(s1>s2) cout<<"hi" ; Another way, in c++, you can use is compare function. string1.compare(String2) results same as : if string1 greater then positive number, if less than, Negetive number, if equal then return 0.
8th Dec 2020, 10:13 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 I can't understand stand your explanation? Plz explain it again sir.
8th Dec 2020, 9:53 PM
Sulaiman Saleh Alzyoud
Sulaiman Saleh Alzyoud - avatar