我想知道如何去分裂一個文本文件,塊大塊和存儲線組作爲單個字符串..例如:如何用c換行符作爲分隔符來解析文件?
我有一個問題的文本文件,其中一些是多個線。在可變數量的行之後(取決於問題佔用的行數),有一個空白行,然後是答案,然後是另一個問題(也可能長於1行),空行,答案。
這樣的事情,其中「Q」是應該被存儲爲單個串和「a」也應該是一個字符串行:
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
aaaaaaaaaaaaaaaaaaaaaaa
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
我試圖讀取一行行,如果組合string line + line
line != ""
。但它令人困惑和混亂,我無法讓它正常工作。
我只是想存儲第一組q
的一個字符串,並把它放在vector[0]
和第一組的a
「在vector[1]
秒。第二組q
的vector[2]
。第二套a
的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;
}
你可以發佈你到目前爲止的代碼嗎? – hmjd
是的,我會發布它。我一直在搞這個,現在看起來像是無稽之談。 – ModdedLife