-4

I've been working on a quiz for my semestral work. It's a simple one since I'm a beginner. And I wanted to let the user insert the character of the option but it's not stopping after the character is inserted and I don't know how to solve it.

int giveAnswera (string answer)
{
    int x = 0;
    cout << "Enter the answer in form of a, b or c." << endl;
    cin >> answer;
    if (cin >> answer == "a")
    {
        cout << "✓" << endl; 
        cout << "Well done." << endl;
        x = x+2;
    }
    else 
    {
        cout << "×" << endl;
        cout << "You're wrong. You get no points." << endl;
        x = x+0; 
    }
 return x;
}
Thorsten Kettner
  • 89,309
  • 7
  • 49
  • 73
  • 5
    Shouldn't `if (cin >> answer == "a")` simply be `if (answer == "a")`? – Thorsten Kettner Jan 10 '17 at 14:19
  • why inputting answer inside the function and passing also a value for the answer via parameter? you can choose one of the two otherwise it is bad idea. also `if (cin >> answer == "a")` doesn't check for the string value but instead it checks whether the input was correct or `correct` doesn't mean "a" but valid data type was assigned, – Raindrop7 Jan 10 '17 at 14:23

2 Answers2

2

In C++11, it doesn't compile.

In C++03, it does compile, but you try to read twice with cin >> answer, and the function is stuck waiting for the second input.
The condition should be just answer == "a".

And since you're not using the value of the function's parameter for anything, you should remove it and use a local variable instead:

int giveAnswera ()
{
    string answer;
    int x = 0;
    cout << "Enter the answer in form of a, b or c." << endl;
    cin >> answer;
    if (answer == "a")
    {
        cout << "✓" << endl; 
        cout << "Well done." << endl;
        x = x+2;
    }
    else 
    {
        cout << "×" << endl;
        cout << "You're wrong. You get no points." << endl;
    }
    return x;
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

You should not use

if(cin >> answer == "a")

instead use

cin >> answer;
if(answer == "a")
Rishabh Gupta
  • 389
  • 6
  • 19