September 1st, 2003, 07:01 PM
How to tell if there's unread info in an istream?
I have a function that parses a command line. Problem is though, I need it to do one thing if supplied with some command line arguments, and another if it isn't. But I'm not sure how to probe the stream to see if there's any data in it. For example,
I could always just read the entire line at the beginning using getline(), then parse the string myself, but I'm trying to put this in a program I already wrote, and I'd rather not make any changes to the command line implementation.
// Forward declaration.
void cmd_help(istream &);
// Parse the command line.
cin >> cmd;
if (cmd == "help")
void cmd_help(istream & in)
// If there's remaining info in the stream, interpret it.
in >> info;
// Interpret the info string.
// Just display the default help message.
cout << ST_HELP;
September 1st, 2003, 07:21 PM
I am far from a C++ IO guru, but isn't there a 'peek' function? If all you want to do is know if the stream is there or not, simply opening it and looking for EOF should tell you that, shouldn't it?
September 2nd, 2003, 02:25 AM
Yeah, there is. Been there done that. Got it working anyways though...
Funny...I got so far as (unsuccessfully) playing with basic_streambuf::sgetc() which is called by peek(). The problem though, is I was testing for the wrong character. You need to test for the trailing newline char, NOT an EOF bit...
Turns out the cin methods flush the buffer _before_ a call, not after. Makes sense I suppose. Sometimes it's the simplest things. Well, usually it's the simplest things...
if (cin.peek() != '\n')
// Remaining data in the buffer.
Last edited by MJEggertson; September 2nd, 2003 at 02:30 AM.