Comparing strings issue | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Comparing strings issue

Hello! Just curious if anyone could possibly help me with the issue I’m having. I’ve started using the .compare function to compare strings for quiz thing I’m making, but for some reason it says the strings are the same when the value is 1, but I know it’s meant to be 0. I’ve copied and pasted the answer multiple times but each time when compared it’s producing a 1 and I don’t understand why.

3rd Apr 2022, 6:08 PM
Dylan Hope
10 Answers
+ 1
EDITED: Dylan Hope, see Simon Sauter's answer. Here is the code after correcting the minor syntax errors. #include <iostream> using namespace std; int main() { string MyAnswer; string Questions[3] = {"a b", "c d", "e f"}; string Answers[3] = {"g h","i j", "k l"}; for(int i = 0; i<3; i++){ cout << Questions[i] <<endl; cin >> MyAnswer; if (MyAnswer.compare(Answers[i]) == 0) cout << "Well Done!"; } return 0; }
3rd Apr 2022, 6:50 PM
Brian
Brian - avatar
+ 4
cin stops reading as soon as it encounters a space. Add cout << MyAnswer; and you'll see that you don't get what you expect. That's why the comparison fails.
3rd Apr 2022, 6:50 PM
Simon Sauter
Simon Sauter - avatar
3rd Apr 2022, 6:56 PM
Simon Sauter
Simon Sauter - avatar
+ 3
You can put a minimal working example on sololearn playground so we can test it
3rd Apr 2022, 6:30 PM
Lisa
Lisa - avatar
+ 2
Please link your code.
3rd Apr 2022, 6:14 PM
Lisa
Lisa - avatar
+ 1
Hi Lisa its not on sololearn but i can type it here: string MyAnswer; string Questions[3] = {the questions}; string Answers[3] = {the answers}; for(int i = 0; i<3; i++){ Cout << Questions[i] <<endl; Cin >> MyAnswer; If (MyAnswer.compare(Answers[i]) == 0 { Cout << “Well Done!”; } Thats what i have atm for for some reason its just always skipping past the well done unless i change 0 to 1
3rd Apr 2022, 6:20 PM
Dylan Hope
3rd Apr 2022, 6:36 PM
Dylan Hope
+ 1
Dylan Hope I created this script for you... Some improvements are required but it captures the essence... https://code.sololearn.com/cY7ExcOK7xLS/?ref=app
5th Apr 2022, 1:46 AM
Sanjay Kamath
Sanjay Kamath - avatar
0
Simon Sauter ohhh ok thanks is there any way around this?
3rd Apr 2022, 6:52 PM
Dylan Hope
- 2
Nk
5th Apr 2022, 9:42 AM
Harshu GK