Sir Jony Sir Jony - 2 months ago 9
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
\n
is flushed, and never ends up in
str
to verify that a lonely
\n
was entered. I'm not curious why this doesn't work; I know why.


How can you verify that a lonely
\n
was entered, hence exiting the
while-loop
?






I know one can do the following:

while (cin >> str);


However:


  • >>
    only takes one word at a time

  • In my actual code, a
    for-loop
    is used, rather than a
    while-loop
    .


Answer

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
}