I have C++ class Question
to hold data from a file questions.txt
of multiple choice questions and answers:
update: I have updated the &operator>> operator overload I have one:
- it only insert first multiple choice question of 2 multiple choice questions"read the first Question "
Data in file questions.txt:
A programming language is used in this Course? 3
1. C
2. Pascal
3. C++
4. Assembly
What compiler can you use to compile the programs in this Course? 4
1. Dev-C++
2. Borland C++Builder
3. Microsoft Visual C++
4. All of the above
I'm trying to insert the multiple answers into a map. I just want to ask how to overload operator>>
to iterate over multiple answers to insert them into a map:
#include <string>
#include <iostream>
#include <sstream>
#include <map>
using namespace std;
class Question
{
string question;
int correctIndex;
map<int,string> answers;
friend std::istream &operator>>(std::istream &is, Question &q) {
getline(is, q.question, '?'); // stops at '?'
is>> q.correctIndex;
string line;
while (getline(is, line) && line.empty()) // skip leading blank lines
;
while (getline(is,line) && !line.empty()) // read until blank line
{
int id;
string ans;
char pt;
stringstream sst(line); // parse the line;
sst>>id>>pt; // take number and the following point
if (!sst || id==0 || pt!='.')
cout << "parsing error on: "<<line<<endl;
else {
getline (sst, ans);
q.answers[id] = ans;
}
}
return is;
}
};
int main()
{
ifstream readFile("questions.txt");//file stream
vector<Question> questions((istream_iterator<Question>(readFile)), istream_iterator<Question>());
}