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.
10 RĂ©ponses
+ 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;
}
+ 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.
+ 4
+ 3
You can put a minimal working example on sololearn playground so we can test it
+ 2
Please link your code.
+ 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
+ 1
+ 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
0
Simon Sauter ohhh ok thanks is there any way around this?
- 2
Nk