J.G-quiz-with-validators

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.9 kB
1
Indexable
Never
#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 ValidateInput {
private:
  char validatedLetter;
  char fixLetterSizes(char answer) { return tolower(answer); }

  char checkProvidedLetter(char answer) {
    validatedLetter = fixLetterSizes(answer);
    return validatedLetter >= 'a' && validatedLetter <= 'c';
  }

  void throwError() {
    cout << "Wpisana odpowiedź jest nieprawidłowa";
    exit(1);
  }

public:
  void runValidators(char answer) {
    if (!checkProvidedLetter(answer)) {
      throwError();
    }
  }

  char retriveValidatedLetter() { return validatedLetter; }
};

class Question {
private:
  sQuestions currentQuestion;
  ValidateInput validator;
  int nr;

  char getAnswer() {
    char answer;
    cout << "Podaj odp:" << endl;
    cin >> answer;
    validator.runValidators(answer);
    return validator.retriveValidatedLetter();
  }

  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;
}