Summary:
A robust, console-based educational tool designed to manage and execute multiple-choice examinations. The system emphasizes modular design, separating the question logic from the engine's execution flow.
Learning Objectives:
Encapsulation: Managing question data and validation through private members and public interfaces.
Object Composition: Utilizing a std::vector of Class Objects to build a dynamic database.
Input Validation: Implementing "fail-safe" console handling to prevent infinite loops during data entry.
The Source Code
This main.cpp is optimized for Code::Blocks using the MinGW toolchain. It includes <limits> for buffer clearing and <iomanip> for score formatting.
#include <iostream> #include <vector> #include <string> #include <limits> #include <iomanip>
using namespace std;
// Class representing a single Multiple Choice Question class Question { private: string text; string options[4]; int correctAnswer; // Index 1-4
public: Question(string q, string opts[4], int ans) { text = q; for(int i = 0; i < 4; i++) options[i] = opts[i]; correctAnswer = ans; }
void display(int qNum) const { cout << "\nQuestion " << qNum << ": " << text << endl; for(int i = 0; i < 4; i++) { cout << " " << (i + 1) << ". " << options[i] << endl; } }
bool checkAnswer(int userChoice) const { return userChoice == correctAnswer; }
int getCorrectAnswer() const { return correctAnswer; } };
class QuizEngine { private: vector<Question> bank; int score;
public: QuizEngine() : score(0) {}
void addQuestion(const Question& q) { bank.push_back(q); }
void run() { cout << "========================================" << endl; cout << " WELCOME TO THE ACADEMIC QUIZ GAME " << endl; cout << "========================================" << endl;
for(size_t i = 0; i < bank.size(); i++) { bank[i].display(i + 1); int choice = getValidInput();
if(bank[i].checkAnswer(choice)) { cout << ">> Correct!" << endl; score++; } else { cout << ">> Wrong. The correct answer was " << bank[i].getCorrectAnswer() << "." << endl; } }
displayResults(); }
private: int getValidInput() { int input; while (true) { cout << "Your Answer (1-4): "; if (cin >> input && input >= 1 && input <= 4) { return input; } else { cout << "[Error] Invalid input. Please enter a number between 1 and 4." << endl; cin.clear(); // Clear error flags cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Discard buffer } } }
void displayResults() { double percentage = (static_cast<double>(score) / bank.size()) * 100; cout << "\n----------------------------------------" << endl; cout << "QUIZ FINISHED!" << endl; cout << "Final Score: " << score << "/" << bank.size() << endl; cout << "Grade: " << fixed << setprecision(2) << percentage << "%" << endl; cout << "----------------------------------------" << endl; } };
int main() { QuizEngine myQuiz;
string o1[] = {"C++", "Java", "Python", "Assembly"}; myQuiz.addQuestion(Question("Which language is known for its manual memory management?", o1, 1));
string o2[] = {"Encapsulation", "Polymorphism", "Recursion", "Inheritance"}; myQuiz.addQuestion(Question("Which of these is NOT a primary pillar of OOP?", o2, 3));
string o3[] = {"MinGW", "Visual Studio", "Code::Blocks", "GCC"}; myQuiz.addQuestion(Question("Which of the following is an Integrated Development Environment (IDE)?", o3, 3));
myQuiz.run();
cout << "\nPress Enter to exit..."; cin.ignore(); cin.get();
return 0; } |
Execution Trace (Sample User Session)
======================================== WELCOME TO THE ACADEMIC QUIZ GAME ========================================
Question 1: Which language is known for its manual memory management? 1. C++ 2. Java 3. Python 4. Assembly Your Answer (1-4): 1 >> Correct!
Question 2: Which of these is NOT a primary pillar of OOP? 1. Encapsulation 2. Polymorphism 3. Recursion 4. Inheritance Your Answer (1-4): x [Error] Invalid input. Please enter a number between 1 and 4. Your Answer (1-4): 3 >> Correct!
Question 3: Which of the following is an Integrated Development Environment (IDE)? 1. MinGW 2. Visual Studio 3. Code::Blocks 4. GCC Your Answer (1-4): 1 >> Wrong. The correct answer was 3.
---------------------------------------- QUIZ FINISHED! Final Score: 2/3 Grade: 66.67% ---------------------------------------- |
Academic "Learning Corner"
1. The MinGW "Input Hang" Fix
In standard C++ console applications, if a user enters a character (like 'x') when the code expects an int, std::cin enters a fail state. If you don't clear it, the program will spin in an infinite loop.
cin.clear() resets the internal error state flags.
cin.ignore(numeric_limits<streamsize>::max(), '\n') wipes the "junk" character out of the keyboard buffer so the next cin >> actually waits for new input.
2. Header Justification
<limits>: Essential for numeric_limits, providing a platform-independent way to clear the input buffer.
<iomanip>: Used for setprecision(2). In academic reporting, providing raw doubles (like 66.666667%) is considered unprofessional; fixed-point notation ensures clean UI.
3. Object Composition
The QuizEngine does not inherit from Question. Instead, it "has-a" collection of questions. This is a fundamental OOP design pattern that makes the code more flexible—you can add 10 or 100 questions without changing the Engine's logic.
eBook ‘14 Beginner Level C++ Projects’ purchase Link: Google Play Store || Google Books
eBook ‘14 Beginner Level C++ Projects’ Promotional Link:
Level Up Your Coding Skills: Master C++ with 14 Hands-On Academic Projects!
For all 2026 published articles list: click here
...till the next post, bye-bye & take care
No comments:
Post a Comment