2011-01-20 60 views
0

我正在尋找一個優雅的方式來解析文件到塊,每個塊創建一個新的文件,例如:如何解析文件來阻止C++

原始文件:

line 1 
line 2 
line 3 

line 4 
line 5 
    line 6 
line 7 

結果:

first file: 
line 1 

second file: 
line 2 
line 3 

third file: 
line 4 
line 5 
    line 6 

fourth file: 
line 7 

感謝

+0

你可以分享你的代碼空的時候,你已經盡力了,提您所面臨的問題(一個或多個)。 – 2011-01-20 05:30:43

+0

嘿,我很難用C++語法編寫。 algortithm不是問題,我只是想避免使用C代碼,並尋找一種方法,用C++代碼編寫文件迭代器或其他東西 – user534976 2011-01-20 05:39:09

回答

1

你可以使用scoped_ptr s到改變輸出文件時,輸入行不以空格開頭:

std::ifstream in("/your/input/file"); 
boost::scoped_ptr<std::ofstream> out(NULL) 
int out_serial = 0; 
std::string line; 
while(std::getline(in, line)) 
{ 
    // test: first character non blank 
    if(! line.empty() && (line.at(0) != ' ' && line.at(0) != '\t')) 
    { 
     std::ostringstream new_output_file; 
     new_output_file << "/your/output/file/prefix_" << out_serial++; 
     out.reset(new std::ofstream(new_output_file.str())); 
    } 
    if(out.get() != NULL) (*out) << line << std::endl; 
} 
2

看起來你可以使用這個算法:

計數的空格數在每行的開頭,如果是小於或等於空格前面的非空行數,打開新文件。

你嘗試過這麼遠嗎?

+0

嘿,我很難用C++語法編寫。該algortithm是沒有問題的,我只是想避免使用C代碼,並尋找一種方式把它寫在文件迭代器什麼的C++代碼... – user534976 2011-01-20 05:35:33

0

如果你的代碼是不正確的預期或您的塊只根據括號沒有空格,可以使用堆棧(STL)。按下左大括號並彈開大括號。打開一個新的文件,每個堆疊成爲