[英]When using std::istream_iterator it seems to skip empty file lines - how do I avoid this if possible?
例如,使用此代碼 - in_file 是在默認模式下打開的 ifstream。
std::istream_iterator<std:string>> file_line(in_file);
std::istream_iterator<std::string> end_stream;
std::for_each(file_line, end_stream, [&](const std::string& s)
{outputLineToFile(output_file_name, processLine(s)); });
對於只包含換行符的行,從不調用謂詞。 應該是,有什么我可以做的嗎?
您的問題的解決方案是使用代理類讀取完整行,無論它是否為空。
然后你可以在這個代理中使用std::istream_iterator
。 使用它,一切都將按照您的預期使用算法。
請參閱下面有關如何執行此操作的簡單示例:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <fstream>
#include <sstream>
class CompleteLine { // Proxy for the input Iterator
public:
// Overload extractor. Read a complete line
friend std::istream& operator>>(std::istream& is, CompleteLine& cl) { std::getline(is, cl.completeLine); return is; }
// Cast the type 'CompleteLine' to std::string
operator std::string() const { return completeLine; }
protected:
// Temporary to hold the read string
std::string completeLine{};
};
std::istringstream inFile{R"(Line 1
Line 2
Line 4
Line 6)"};
int main()
{
// Show result, so all lines to the user
std::copy(std::istream_iterator<CompleteLine>(inFile), std::istream_iterator<CompleteLine>(), std::ostream_iterator<std::string>(std::cout,"\n"));
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.