开发者

C++ if...then statement

So I'm trying to make a simple application that quizzes the user. It asks a question and the user answers 1, 2, 3, or 4. The app then takes that answer and if it is correct adds +1 to the total_score which will be displayed at the end. Everything looks sound to me, but when I run it and I get to the if (q1_valid == false) part it skips the cout and runs the goto no matter if q1_valid is true or false.

#include <iostream>

using namespace std;

int main()
{
    int q1_answer;
    int total_score;
    bool q1_correct;
    bool q1_valid;

    Question_1:
    cout << "Question 1 (#3 is correct)" << endl;
    cout << "1.) Answer 1" <<endl;
    cout << "2.) Answer 2" <<endl;
    cout << "3.) Answer 3" <<endl;
    cout << "4.) Answer 4" <<endl;
    cin >> q1_answer;

    if (q1_answer == 1)
    q1_correct = false;
    q1_valid = true;

    if (q1_answer == 2)
    q1_correct = false;
    q1_valid = true;

    if (q1_answer == 3)
    q1_correct = true;
    q1_valid = true;

    if (q1_answer == 4)
    q1_corre开发者_StackOverflowct = false;
    q1_valid = true;

    if (q1_valid == false)
    cout << "Invalid answer." <<endl;
    goto Question_1;

    if (q1_correct == true)
    cout << "Correct!" <<endl;
    (total_score + 1);
    goto Question_2;

    if (q1_correct == false)
    cout << "Incorrect." <<endl;
    goto Question_2;

    if (q1_valid == false)
    goto Question_1;

    Question_2:
    cout<< "Q2" <<endl;
cin.ignore();
cin.ignore();
}


I have a few tips here:

  1. If... then is a conditional, not a loop. Sorry, that's just me being slightly picky. ;)
  2. Never, ever, ever, ever use goto. ADVANCED USAGE: only use goto when there's a damned good reason to.
  3. When testing boolean values, you don't need "== true" or "== false".
  4. It looks like you haven't learned how to use the else statement yet. That's going to make your program a lot easier to read, debug, and understand.
  5. Brackets are also necessary, as noted above.


You need to use brackets:

if (q1_valid == false) {
  cout << "Invalid answer." <<endl;
  goto Question_1;
}

If you don't use the brackets, the if only executes the first statement directly following it, if the if condition evaluates to true.


You don't have braces around the statements after the if, so only the first statement is conditional. In this case, that means that "q1_valid=true;" runs no matter what the answer is.

if (q1_answer == 4) {
 q1_correct = false;
 q1_valid = true;
}

You need an editor which shows you this by indentions.

emacs will, for example


Brackets for the if statement are required.

Have you considered using the switch statement:

switch (q1_answer){
  case 1:
    q1_correct = false;
    q1_valid = true;
    break;
  case 2:
    q1_correct = false;
    q1_valid = true;
    break;
  case n:
    //...
    break;
}


Don not forget to use brackets.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜