[英]How to Parse A file to block in 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
謝謝
看來您可以使用以下算法:
計算每行開頭的空格數,如果小於或等於前一個非空行中的空格數,請打開一個新文件。
你試過什么了?
當輸入行不是以空格開頭時,可以使用scoped_ptr
更改輸出文件:
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;
}
如果您的代碼使用不正確或您的代碼塊僅基於大括號而不是空格,則可以使用堆棧(STL)。 推開撐桿,然后彈起關閉撐桿。 每次堆棧為空時打開一個新文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.