我有C++ Question
類從選擇題和答案文件questions.txt
保存數據:如何使用輸入流重載將項目插入到地圖成員中?
更新: 我已經更新了&操作>>運算符重載我有一個:
- 它只插入2個選擇題的第一個選擇題「閱讀第一個問題」
文件中的數據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
我想插入多個答案成圖。我只想問如何重載operator>>
遍歷多個答案將它們插入到地圖:
#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>());
}
嗨@Christophe我有更新的問題,你可以看看嗎? – NinjaDeveloper
@NinjaDeveloper糟糕對不起,我有點快:第一個循環結束或者如果到達線的EOF不是空的。在後一種情況下(例如,您的答案爲「1. C」),您需要首先處理行,然後再獲取新行。我已經相應更新。 – Christophe