Sir Jony Sir Jony - 1 month ago 5x
C++ Question

Figuring out whether `cin.getline()` succeeds

Here's the basic code snippet:

while (true)
cin.getline(str, STRSIZE);
if (str[0] == '\n') { break; }

Essentially, when the user inputs just a lonely return key, the loop is supposed to end.
Of course, this code doesn't work, because the
is flushed, and never ends up in
to verify that a lonely
was entered. I'm not curious why this doesn't work; I know why.

How can you verify that a lonely
was entered, hence exiting the

I know one can do the following:

while (cin >> str);


  • >>
    only takes one word at a time

  • In my actual code, a
    is used, rather than a


If cin.getline() fails to read a line, cin will be in a state of error.

You can use:

while (cin.getline(str, STRSIZE))
   if ( str[0] == '\0' ) { break; }

   // Use str