J.G-quiz-from-file
unknown
c_cpp
3 years ago
2.3 kB
4
Indexable
#include <iostream> #include <string> #include <stdlib.h> #include <fstream> using namespace std; const int QUSTION_COUNT = 3; struct sQuestions { string data; string a, b, c; char correct; }; class Question { private: sQuestions currentQuestion; int nr; char getAnswer() { char answer; cout << "Podaj odp:" << endl; cin >> answer; return answer; } void loadFromFile(string const name = "pytania.txt") { fstream file; string currentLine; file.open(name, ios::in); if (!file.good()) { cout << "Błąd otwarcia"; exit(1); } string snr = to_string(nr); snr = "[" + snr + "]"; while (getline(file, currentLine)) { if (currentLine == snr) { getline(file, currentLine); currentQuestion.data = currentLine; getline(file, currentLine); currentQuestion.a = currentLine; getline(file, currentLine); currentQuestion.b = currentLine; getline(file, currentLine); currentQuestion.c = currentLine; remove(currentLine.begin(), currentLine.end(), ' '); getline(file, currentLine); currentQuestion.correct = currentLine[0]; } } } public: bool validateAnswer() { return getAnswer() == currentQuestion.correct; } void displayQuestion(int index) { cout << to_string(index + 1) + ") " << currentQuestion.data << endl; cout << " a) " + currentQuestion.a << endl; cout << " b) " + currentQuestion.b << endl; cout << " c) " + currentQuestion.c << endl; } Question(int _nr) { nr = _nr; loadFromFile(); } }; class Quiz { public: void start() { showQuestions(); showResult(); } private: char selectedOption; int points; void showQuestions() { cout << "Quiz: " << endl; for (int i = 0; i < QUSTION_COUNT; i++) { Question question = Question(i + 1); question.displayQuestion(i); incrementPointIfAnswerValid(question.validateAnswer()); } } void showResult() { cout << "Gratulacje!!! " << endl; cout << "Twój wynik to: " << points; } void incrementPointIfAnswerValid(bool isValid) { if (isValid) { points++; } } }; int main() { Quiz quiz = Quiz(); quiz.start(); return 0; }
Editor is loading...