if-else statement problem

I am having trouble with my if else statements. I want it to print You win for the right answer, and you lose for anything else. To me, the logic should work. The computer disagrees however. Here is the code:

#include <iostream>
#include <string>
using namespace std;

string myquiz()
{
string youranswer;
cout << "Enter answer: "; //the question I am asking the user
cin >> youranswer; // their answer
getline (cin, youranswer);


return youranswer;
}

int main()
{
if (myquiz() == "yes") // check to see if the answer if correct
cout << "You win! " << endl;
else //having problems here. The compiler prints you lose even if answer is right...
cout << "You lose! " << endl;
return 0;
}

Any suggestions? Thanks in advance.
closed account (iLUjLyTq)
Try using the compare() function of string class for comparing strings:

if(!myquiz().compare("yes")) ...

The result will be 0 if they are equal, thus the negate operator in the if statement.
Last edited on
you used both cin and getline back to back. pick only one and it should work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;

string myquiz()
{
    string youranswer;
    cout << "Enter answer: "; //the question I am asking the user
    cin >> youranswer; // their answer
   // getline (cin, youranswer); dont need this you already called cin

    return youranswer;
}

int main()
{
    if (myquiz() == "yes") // check to see if the answer if correct
        cout << "You win! " << endl;
    else //having problems here. The compiler prints you lose even if answer is right...
        cout << "You lose! " << endl;
    
    return 0;
}
Last edited on
@acorn: thanks! that did the trick. I think I read my book wrong :P
Topic archived. No new replies allowed.