I am trying to create a program that creates quizzes and stores the data into a file. This is my first attempt my code is sloppy and possibly more issues than what I want to fix. The primary issue I can not seem to find a solution for is when I use file << user_question;
it just stores the question the user wants but I want to also write next to the question the current number the question is. An example of my desired output is this "1.) How are mushrooms grown?" As the user generates more questions the number will change as the current_numbered_question variable goes up.
`
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int number_of_questions;
int current_numbered_question = 0;
int user_choice;
string user_question;
string user_answer;
void quizBuilder();
//Step 1. Welcome user and explain how to use the quiz maker
//Step 2. How many questions would you like to ask?
/*
* all the question options and records answers and kills program
* once they have met the number of questions
*/
//step 3. Begin with asking what type of question it will be.
//- multiple choice
//- short written answer
//- connect defintion to word
//- True or False
//step 3.
void multipleChoice() {
fstream file;
if (!file)
{
cout << "Error when opening file.";
}
file.open("quiz.txt", ios::out);
cout << "What is your question?\n";
cin.ignore();
getline(cin, user_question);
if (file.is_open())
{
file << user_question;
cout << "What is the first multiple choice answer you would like?\n";
getline(cin, user_answer);
file << user_answer;
}
return;
}
void quizBuilder() {
do {
cout << "What type of question would you like to create?\n";
cout << "1. multiple choice\n";
cout << "2. short written answer\n";
cout << "Type of question: ";
cin >> user_choice;
cout << "\n\n";
current_numbered_question ;
if (user_choice == 1) {
multipleChoice();
}
else {
cout << "Issues";
}
} while (current_numbered_question != number_of_questions);
}
string greeting() {
cout << "Welcome to the Quiz Maker!\n";
cout << "How many questions would you like to make for this quiz?\n";
cout << "Number of questions: ";
cin >> number_of_questions;
cout << "\n\n";
quizBuilder();
return 0;
}
int main()
{
fstream file; //This library creates and manages files using c
file.open("quiz.txt", ios::out); //ios::out is write mode
cout << "File was successfully created.\n\n";
file.close();
greeting();
return 0;
}
`
I tried several different youtube videos on strings, concatentaion, file write and read using variables but none seemed to produce what I want or just errors.
Simply put when user provides the question they want written into the file it gets numbered and then stored.
Example of output:
12.) What is the Earth's circumference?
CodePudding user response:
Use the <<
operator multiple times like this:
file << current_numbered_question << ".) " << user_question;