Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Created May 18, 2013 23:57
Show Gist options
  • Select an option

  • Save Rhomboid/5606151 to your computer and use it in GitHub Desktop.

Select an option

Save Rhomboid/5606151 to your computer and use it in GitHub Desktop.
silly question/answer quiz example (C++11)
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <cassert>
using namespace std;
class Quiz {
vector<pair<string, string>> questions;
vector<string> answers;
public:
Quiz(const string& filename) {
ifstream f { filename };
string answer, question;
while(getline(f, answer) && getline(f, question)) {
questions.emplace_back(question, answer);
answers.emplace_back(answer);
}
}
size_t num_questions() const { return questions.size(); }
bool ask(size_t question_num, size_t num_answers = 3) {
// get and print the question
assert(question_num < questions.size());
const string& ques = questions[question_num].first;
const string& correct_ans = questions[question_num].second;
cout << "Question: " << ques << "\n";
// build a vector containing the correct answer and (num_answers - 1) randomly chosen incorrect answers
partition(begin(answers), end(answers), [&] (const string& ans) { return ans == correct_ans; });
random_shuffle(begin(answers) + 1, end(answers));
vector<string> possible_answers(begin(answers), begin(answers) + min(answers.size(), num_answers));
// display the choices in random order
random_shuffle(begin(possible_answers), end(possible_answers));
for(size_t i = 0; i < possible_answers.size(); ++i)
cout << i + 1 << ". " << possible_answers[i] << "\n";
// take input until a valid response is seen
for(string response; cout << "Answer: " && getline(cin, response); cout << "Bad input, try again.\n") {
istringstream ss(response);
size_t i;
if(ss >> i && i >= 1 && i <= possible_answers.size()) {
if(possible_answers[i - 1] == correct_ans) {
cout << "Correct\n\n";
return true;
} else {
cout << "Wrong\n\n";
return false;
}
}
}
return false;
}
};
int main(int argc, char **argv)
{
assert(argc == 2);
Quiz q { argv[1] };
size_t correct = 0;
for(size_t i = 0; i < q.num_questions(); ++i)
correct += q.ask(i);
cout << "\n\nYou got " << correct << " out of " << q.num_questions() << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment