+ 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?
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.
+ 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?
+ 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
+ 1
Ashfaq Reshad then you can just manipulate value of "I" accordingly š
https://code.sololearn.com/cPjEOgrFAxpL/?ref=app
+ 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.
+ 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
+ 1
Arsenic thank you <3
0
Arsenic i want the output like you said above. -1,0,1
That's i want
0
Arsenic It's giving the same value for all test cases.
1
1
1
šŖšŖ