How to read until EOF from cin in C++

c++, input, iostream

Solution

The only way you can read a variable amount of data from `stdin` is using loops. I've always found that the `std::getline()` function works very well:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout << line << std::endl;
}

By default `getline()` reads until a newline. You can specify an alternative termination character, but EOF is not itself a character so you cannot simply make one call to `getline()`.

Problem

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?

Original source

Related problems