In: Computer Science
Create a question bank. The language is visual studio c++.
Description:
Question bank computerizes the MCQ based exams.It takes input from
a file having questions and their answers
and presents randomly before the exam takers.
Required skill set: OOP, STL(Vector), Arrays and file handling
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
class MCQ
{
private:
string question, opt1, opt2, opt3, opt4;
char correct;
public:
MCQ()
{
this->question = "";
this->opt1 = "";
this->opt2 = "";
this->opt3 = "";
this->opt4 = "";
this->correct = 0;
}
MCQ(string ques, string opt1, string opt2, string opt3, string opt4, char corr)
{
this->question = ques;
this->opt1 = opt1;
this->opt2 = opt2;
this->opt3 = opt3;
this->opt4 = opt4;
this->correct = corr;
}
string getQuestion(){ return this->question; }
string getOption1(){ return this->opt1; }
string getOption2(){ return this->opt2; }
string getOption3(){ return this->opt3; }
string getOption4(){ return this->opt4; }
char getCorrect(){ return this->correct; }
string toString()
{
stringstream ss;
ss << "Question: " << question << " ?" << endl << "a. " << opt1 << "\nb. " << opt2 << "\nc. " << opt3 << "\nd. " << opt4;
return ss.str();
}
};
void splitIntoTokens(string const &str, const char delimiter, vector<string> &res);
int main()
{
ifstream inFile("questions.txt");
vector<MCQ> mcqs;
int correctAnswers = 0;
if(!inFile.is_open())
{
cout << "Could not open file: questions.txt" << endl;
exit(0);
}
string line;
while(getline(inFile, line))
{
const char delimiter = ',';
vector<string> result;
splitIntoTokens(line, delimiter, result);
string question = result[0];
string option1 = result[1];
string option2 = result[2];
string option3 = result[3];
string option4 = result[4];
char correct = result[5][0];
mcqs.push_back(MCQ(question, option1, option2, option3, option4, correct));
}
inFile.close();
cout << endl;
int nQuestions = mcqs.size();
char yesNo;
do
{
int picker = rand() % nQuestions + 0;
cout << mcqs[picker].toString() << endl;
char correct = mcqs[picker].getCorrect();
char choice;
cout << "Your answer (a/b/c/d): ";
cin >> choice;
while(choice != 'a' && choice != 'b' && choice != 'c' && choice != 'd')
{
cout << choice << " is not a valid choice" << endl;
cout << "Your answer (a/b/c/d): ";
cin >> choice;
}
if(choice == correct)
correctAnswers++;
cout << endl << "Continue?[y/n]: ";
cin >> yesNo;
if(yesNo == 'N' || yesNo == 'n')
{
cout << "\nYour score: " << correctAnswers << endl << "Thank you...Good Bye!\n";
exit(0);
}
cout << endl;
}while(yesNo != 'N' || yesNo != 'n');
}
void splitIntoTokens(string const &str, const char delimiter, vector<string> &res)
{
stringstream ss(str);
string s;
while(getline(ss, s, delimiter))
{
res.push_back(s);
}
}
**************************************************************** SCREENSHOT ***********************************************************
INPUT FILE (questions.txt):