One function that would shorten the code is a checkAnswer() function:
1 2 3 4 5 6 7 8
|
void checkAnswer(char correctAnswer, char userAnswer)
{
if (correctAnswer == userAnswer) {
cout << " You got the correct answer!\n";
} else {
cout << "Wrong Answer!\n";
}
}
|
Then lines 25-38 become
checkAnswer(ans, 'D');
. Lines 44-57 become
checkAnswer(ans,'C');
etc.
By the way, you don't initialize the characters easy, medium and hard, nor do you tell the user what characters they should enter for each of these.
Once you get this working, consider changing it so that the questions and correct answers are stored in a text file instead of the code. The file might be formatted like this:
- each question consists of:
- a line that gives the difficulty: Easy, Medium or Hard.
- a line that contains one character that is the correct answer.
- N lines that are the question
- a blank line. This signals the end of the question.
The main part of hte program then becomes something like this:
1 2 3 4 5 6 7
|
while (cin >> question) {
if (question.difficulty == requestedDifficulty) {
cout << question.text;
cin >> ans;
checkAnswer(question.answer, ans);
}
}
|