I was wondering how I would go about splitting a text file, chunk by chunk, and storing groups of lines as a single string.. For example:
I have a text file of questions, some of which are multiple lines. After a variable number of lines (depending on how many lines the question takes up) there is a blank line, then the answer, followed by another question (which could also be longer than 1 line), blank line, answer.
Something like this, where "q" are lines that should be stored as a single string and "a" should also be a single string:
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
aaaaaaaaaaaaaaaaaaaaaaa
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
I tried reading line by line, combining string line + line if line != "". But it got confusing and messy and I couldn’t ever get it to work correctly.
I simply want to store the first set of q‘s as a single string and put it in vector[0] and the first set of a‘s in vector[1]. The second set of q‘s in vector[2]. The second set of a‘s in vector[3].. and so on. Both the q’s and the a’s can be several lines.
Any suggestions or help will be much appreciated!
#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;
}
I tweaked the code a bit and got it to work!
I changed the way I approached cycling through the lines of the text file, changing it to while (!infile.eof()) and manually got the lines. I also added a statement to detect if there was a new line. I also had to reposition where I reset the string variables back to “”.
Thanks for the suggestions! Heres the solution code: