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 Respuestas
+ 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