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?
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: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().
Wait, am I understanding you correctly? You're using cin for keyboard input, and you want to stop reading input when the user enters the EOF character? Why would the user ever type in the EOF character? Or did you mean you want to stop reading from a file at the EOF?
If you're actually trying to use cin to read an EOF character, then why not just specify the EOF as the delimiter?
If you mean to stop reading from a file at the EOF, then just use getline and once again specify the EOF as the delimiter.
One option is to a use a container, e.g.
and redirect all input into this collection until
EOF
is received, i.e.However, the used container might need to reallocate memory too often, or you will end with a
std::bad_alloc
exception when your system gets out of memory. In order to solve these problems, you could reserve a fixed amountN
of elements and process these amount of elements in isolation, i.e.Probable simplest and generally efficient:
If needed, use stream of other types like
std::ostringstream
as buffer instead of standard output stream here.