开发者

Putting a switch inside of do...while

开发者 https://www.devze.com 2023-03-09 03:53 出处:网络
So I have a do... while statement that is supposed to repeat unless the user enters one of four things. Those four things have a break and they set the variable that controls the while to true, where

So I have a do... while statement that is supposed to repeat unless the user enters one of four things. Those four things have a break and they set the variable that controls the while to true, where the default is false. If the user does not enter one of the four answers, the variable will stay false, which should make the do...while start again. It doesn't.

#include <string>
#include <iostream>

using namespace std;

int main()
{
    int q5_answer = 1;
    int q5_answerU;
    int total_score;
    bool q5_valid = false;

    //Question_5:
    do
    {
        cout << "Question 5 (#1 is correct)" <<endl;
        cout << "1.) Answer 1" <<endl;
        cout << "2.) Answer 2" <<endl;
        cout << "3.) Answer 3" <<endl;
        cout << "4.) Answer 4" <<endl;
        cin >> q5_answerU;

        switch (q5_answerU)
        {
   开发者_开发百科     case 1:
            cout << "Correct!" <<endl;
            q5_valid = true;
            (total_score = total_score + 1);
            break;
        case 2:
            cout << "Incorrect" <<endl;
            q5_valid = true;
            break;
        case 3:
            cout << "Incorrect" <<endl;
            q5_valid = true;
            break;
        case 4:
            cout << "Incorrect" <<endl;
            q5_valid = true;
            break;
        default:
            cout << "Invalid answer" <<endl;
        }
    } while (q5_valid = false);
}


The condition inside the while is an "accidental" assignment, not a comparison. It needs to read while (q5_valid == false) or more idiomatic while (!q5_valid).


This is not a boolean expression:

q5_valid = false

It sets the variable q5_valid to false and also returns false. Replace it by:

!q5_valid

or

q5_valid == false

Which are the same. The former is better for readability.

0

精彩评论

暂无评论...
验证码 换一张
取 消