1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
#include <iostream> #include <string> #include <vector> using namespace std; // Structure to hold a question and its answer struct Question { string questionText; string answer; }; // Function to ask a question and get the user's answer bool askQuestion(Question q) { string userAnswer; cout << q.questionText << endl; cout << "Your answer: "; getline(cin, userAnswer); // Compare user's answer to the correct answer if (userAnswer == q.answer) { cout << "Correct!" << endl; return true; } else { cout << "Wrong! The correct answer is: " << q.answer << endl; return false; } } int main() { // List of questions for the quiz vector<Question> quiz = { {"What is the capital of France?", "Paris"}, {"What is 9 + 10?", "19"}, {"Who wrote 'Romeo and Juliet'?", "Shakespeare"}, {"What is the largest planet in our solar system?", "Jupiter"} }; int score = 0; cout << "Welcome to the Quiz Game!" << endl; cout << "=========================" << endl; // Loop through each question for (size_t i = 0; i < quiz.size(); ++i) { cout << "Question " << i + 1 << ": " << endl; if (askQuestion(quiz[i])) { ++score; } cout << endl; } // Display the final score cout << "Quiz over!" << endl; cout << "Your final score is: " << score << " out of " << quiz.size() << endl; return 0; } |
Explanation
- Structure Definition:
- A
struct
namedQuestion
is defined to hold each quiz question and its corresponding correct answer. This helps to keep the question and answer logically grouped together.
- A
- askQuestion Function:
- This function takes a
Question
object as input, displays the question, and prompts the user for an answer. It compares the user’s input with the correct answer and returnstrue
if the answer is correct, otherwisefalse
. It also prints whether the user’s answer was correct or wrong.
- This function takes a
- Main Function:
- The
main()
function starts by initializing a vector ofQuestion
objects that contain the quiz questions and answers. - It then welcomes the player and starts the quiz by iterating over the list of questions using a
for
loop. For each question, it calls theaskQuestion
function and updates the score based on the player’s response. - Finally, after all the questions have been answered, it displays the player’s total score.
- The