Need help again

what this function will do, l mean what is the function of line 1,2,3 as l mention below.
and what is status flag?
any help would be appreciated.

int getInteger()
{
int n;

while (!(cin >> n)) //line 1
{
cin.clear(); //line 2 // not valid, clear status flags
cin.ignore(1000, '\n'); //line 3 // discard rest of line
}

return n;
}
Hello daimkhalid07,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.

The while loop will be true if the "cin" stream fails. This could happen because "cin >> n" if considered a formatted input meaning that the "cin" is expecting a numerical entry, so if a letter is entered "cin" will fail.

When you enter the while loop, which continues as long as "cin" fails, line 2 will clear the state bits associated with the stream so it can be used again.

Line 4 may or may not clear the rest of the line. It would depend on how many characters were entered. If this was < 1000 then it will clear the input buffer including the "\n". Your line 3 should work, but the more accepted use of "cin.ignore" is:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.

If the next input is good the while loop will fail and and the function will return n.

Hope that helps,

Andy
"Your line 3 should work, but"

that should read, "Chervil's line 3".
Topic archived. No new replies allowed.