我想知道如何将文本文件逐块拆分,并将行组存储为单个字符串。例如:
我有一个问题文本文件,其中一些是多行的。在可变数量的行之后(取决于问题占用的行数)有一个空白行,然后是答案,然后是另一个问题(也可能比 1 行长),空白行,答案。
像这样的东西,其中“q”是应该存储为单个字符串的行,而“a”也应该是单个字符串:
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
aaaaaaaaaaaaaaaaaaaaaaa
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
我尝试逐行阅读,结合string line + line
if line != ""
。但它变得混乱和混乱,我无法让它正常工作。
我只是想将第一组q
's 存储为单个字符串并将其放入,vector[0]
并将第一组a
's 放入vector[1]
. 第二组q
's in vector[2]
. 第二组a
's in vector[3]
.. 以此类推。q 和 a 都可以是多行。
任何建议或帮助将不胜感激!
#include <vector>
#include <fstream>
#include <iostream>
#include "Question.h"
#include <iomanip>
using namespace std;
int main(int argc, char * argv[]){
ifstream infile;
string filename = "questions.txt";//manually set for testing.
//cout<<"Enter the questions file: ";
//cin>>filename;
infile.open(filename.c_str());
if (!infile){
cout<<"error"<<endl;
return 0;
}
else {
cout<<"file opened!"<<endl;
}
vector<string> myvector;
string line;
string additionalLine;
int totalLines = 0;
while(getline(infile,line)){
totalLines++;
}
cout<<"total lines: "<<totalLines<<endl;
/*
while(getline(infile,line,'\n')){
cout<<line<<endl;
}
*/
while(getline(infile,line,\n)){
if (line == ""){
cout<<"empty"<<endl;
}
else {
cout<<"line is not empty"<<endl;
additionalLine = additionalLine + line;
}
if (line != ""){
myvector.push_back(additionalLine);
}
}
for(int i=0; i < (myvector.size()); i++){
cout<<myvector[i]<<endl;
}
//TESTING
cout<<"Question: "<<endl;
cout<<myvector[0]<<endl;
cout<<"Answer: "<<endl;
cout<<myvector[1]<<endl;
return 0;
}