简体   繁体   中英

When using std::istream_iterator it seems to skip empty file lines - how do I avoid this if possible?

Using this code for example - in_file is an ifstream opened in default mode.

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)); });

The predicate is never called for lines that just include newline. Should it be and is there anything I can do to make it?

The solution to your problem is to use a Proxy Class to read a complete line, whether it is empty or not.

Then you can use the std::istream_iterator with this proxy. Using that, everything will work with algorithms as you expect.

Please see below a simple example on how to do that:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM