I am coding a program that reads data directly from user input and was wondering how could I (without loops) read all data until EOF from standard input. I was considering using cin.get( input, '\0' )
but '\0'
is not really the EOF character, that just reads until EOF or '\0'
, whichever comes first.
Or is using loops the only way to do it? If so, what is the best way?
Sad side note: I decided to use C++ IO to be consistent with boost based code. From answers to this question I chose
while (std::getline(std::cin, line))
. Using g++ version 4.5.3 (-O3) in cygwin (mintty) i got 2 MB/s throughput. Microsoft Visual C++ 2010 (/O2) made it 40 MB/s for the same code.After rewriting the IO to pure C
while (fgets(buf, 100, stdin))
the throughput jumped to 90 MB/s in both tested compilers. That makes a difference for any input bigger than 10 MB...Using loops:
resource
After researching KeithB's solution using
std::istream_iterator
, I discovered thestd:istreambuf_iterator
.Test program to read all piped input into a string, then write it out again:
You can use the std::istream::getline() (or preferably the version that works on std::string) function to get an entire line. Both have versions that allow you to specify the delimiter (end of line character). The default for the string version is '\n'.
You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.