I'm running myself through a C++ text book that I have as a refresher to C++ programming. One of the practice problems (without going into too much detail) wants me to define a function that can be passed ifstream or cin (e.g. istream) as an argument. From there, I have to read through the stream. Trouble is, I can't figure out a way to have this one function use cin and ifstream to effectively find the end of the stream. Namely,
while(input_stream.peek() != EOF)
isn't going to work for cin. I could rework the function to look for a certain phrase (like "#End of Stream#" or something), but I think this is a bad idea if the file stream I pass has this exact phrase.
I have thought to use function overloading, but so far the book has mentioned when it wants me to do this. I'm probably putting too much effort into this one practice problem, but I enjoy the creative process and am curious if there's such a way to do this without overloading.
cin. eof() test if the stream has reached end of file which happens if you type something like Ctrl+C (on Windows), or if input has been redirected to a file etc. To test if the input contains an integer and nothing but an integer, you can get input first into a string and then convert that with a stringstream.
First, cin.eof() returns 1 if you tried to read something but were at the end of file. Second, cin.clear() is used to "clear the error state" of cin.
The way you do that depends on the terminal application, which is typically part of the operating system. On Windows, ctrl-Z tells the terminal application that you're at the end of your input. On Unix systems, it's ctrl-D .
the 'peek' function on input streams (in your case cin ) retrieves the next character from the stream without actually consuming it. That means that you can "preview" the next character in the input, and on the next call to any consuming operation (overloaded operator >> or cin.
eof()
does work for cin. You are doing something wrong; please post your code. One common stumbling block is that eof
flag gets set after you try to read behind the end of stream.
Here is a demonstration:
#include <iostream>
#include <string>
int main( int, char*[] )
{
std::string s;
for ( unsigned n = 0; n < 5; ++n )
{
bool before = std::cin.eof();
std::cin >> s;
bool after = std::cin.eof();
std::cout << int(before) << " " << int(after) << " " << s << std::endl;
}
return 0;
}
and its output:
D:>t
aaaaa
0 0 aaaaa
bbbbb
0 0 bbbbb
^Z
0 1 bbbbb
1 1 bbbbb
1 1 bbbbb
(EOF can be generated with Ctrl-Z on Windows and Ctrl-D on many other OSes)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With