C++
Adding questions
Learn to add questions with the addQuestion method.
Adding questions
Now we add the ability to add questions to the Quiz class. We store questions in a std::vector<Question> and add new ones with an addQuestion method.
Example: void addQuestion(std::string text, std::string answer) { questions.push_back({text, answer}); }. Here push_back creates a new Question and appends it to the vector. In main you add a question with quiz.addQuestion("Capital?", "Ankara");. Below the previous lesson's "Quiz ready" output we print the question count.
vector and push_back
std::vector provides a dynamic array in C++. The push_back method appends an element; size() returns the element count.
We add a std::vector<Question> questions; member to the Quiz class from the previous lesson. We add two questions and print the count with questions.size(). This sets up the quiz's data structure. In the next lessons we will play the questions and calculate the score.
Exercise Add the addQuestion method to Quiz
Take the previous lesson's Question and Quiz skeleton. Add a std::vector<Question> questions; member and a void addQuestion(std::string text, std::string answer) method under public: in Quiz; the body is questions.push_back({text, answer});. In main create a Quiz, add two questions and write std::cout << "Quiz ready" << std::endl; std::cout << quiz.questions.size() << " questions added";.
Show example solution
#include <iostream>
#include <string>
#include <vector>
struct Question {
std::string text;
std::string answer;
};
class Quiz {
public:
std::vector<Question> questions;
void addQuestion(std::string text, std::string answer) {
questions.push_back({text, answer});
}
};
int main() {
Quiz quiz;
quiz.addQuestion("Capital?", "Ankara");
quiz.addQuestion("Largest planet?", "Jupiter");
std::cout << "Quiz ready" << std::endl;
std::cout << quiz.questions.size() << " questions added";
return 0;
}
Test yourself
-
Complete the addQuestion call
quiz.____("Capital?", "Ankara");
Show answer
quiz.addQuestion("Capital?", "Ankara");
-
Match each piece to its role
- std::vector<Question>
- Question list
- push_back
- Append to end
- size()
- Element count
- addQuestion
- Adding method
-
What does push_back do?
questions.push_back({text, answer});
- Appends an element to the end
- Shrinks the vector
- Removes the first element
- Returns an index
Show answer
Appends an element to the end — push_back appends a new element to the end of the vector.
Next lesson: Running the quiz