+ 1

What should i improve on this code?

this code giving me some garbage value for some test cases: #include <bits/stdc++.h> using namespace std; int main() { string str1, str2; int i; cin >> str1 >> str2; i= str1.compare(str2); cout << i << endl; return 0; } for these test cases: abcdefg AbCdEfF abs Abz aaaa aaaA these test cases giving me garbage value. What can i do here?

4th May 2020, 3:54 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
9 Answers
+ 3
string::compare function returns a signed integral instead of Boolean indicating the relation between the strings Let return value be "x", so if x = 0 -> They compare equal x <0 -> Either the value of the first character that does not match is lower in theĀ compared string, or all compared characters match but theĀ compared stringĀ is shorter. x >0 -> Either the value of the first character that does not match is greater in theĀ compared string, or all compared characters match but theĀ compared stringĀ is longer.
4th May 2020, 4:10 AM
Arsenic
Arsenic - avatar
+ 1
Arsenic Thank youā¤ But how can i get the Correct value from this code? What should be the change? I tried many different ways but its giving me like 32 or 30202 something like this? What should i change on this code if you tell?
4th May 2020, 4:20 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
+ 1
Ashfaq Reshad that depends on what you want as output. If you want to only check weather both strings are equal or not then you can just use one if statement for thatšŸ‘‡ https://code.sololearn.com/c2gyGMoJC7o2/?ref=app
4th May 2020, 4:24 AM
Arsenic
Arsenic - avatar
+ 1
Ashfaq Reshad then you can just manipulate value of "I" accordingly šŸ‘‡ https://code.sololearn.com/cPjEOgrFAxpL/?ref=app
4th May 2020, 4:31 AM
Arsenic
Arsenic - avatar
+ 1
That's because comparisons that are happening are case sensitive and they are falling under catagory of "the value of the first character that does not match is greater in theĀ compared string" which returns a positive value hence the output is one everytime.
4th May 2020, 4:43 AM
Arsenic
Arsenic - avatar
+ 1
Ashfaq Reshad if you don't want comparisons to be case sensitive then you can simply convert both of the string into lowercase/uppercase and then compare them HerešŸ‘‡ https://code.sololearn.com/cx56WpEylJ7g/?ref=app
4th May 2020, 4:59 AM
Arsenic
Arsenic - avatar
+ 1
Arsenic thank you <3
4th May 2020, 5:07 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
0
Arsenic i want the output like you said above. -1,0,1 That's i want
4th May 2020, 4:26 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
0
Arsenic It's giving the same value for all test cases. 1 1 1 šŸ˜ŖšŸ˜Ŗ
4th May 2020, 4:34 AM
Ashfaq Reshad
Ashfaq Reshad - avatar