Please explain this piece of code to me

Hi all, I am trying very hard to learn to program and have been setting a lot of little challenges for myself to help me practice(its going pretty well). Anyway, when I hit a wall with something I don't know how to do yet that we haven't learned in class, I go online and look around. So far this forum has been a very helpful resource as there are a lot of people like me.

Anyway, my latest hurdle has been a sort of number-checker that makes sure my imaginary users enter numbers and not, you know, letters.

I found this piece of code on this forum:

1
2
3
4
5
6
7
8
9
10
11

cout << "Enter two integers: ";
    int x = 0;
    while(!(cin >> x))
	{
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Invalid input.  Try again: ";
    }
    cout << "You enterd: " << x << endl;


And had no problems making it work. But the original thread it was in did not go into detail about exactly what is going on, here, and I have a little personal rule about not using code I can't understand(this seemed like a wise way to ensure I'm actually learning).

In particular, on this line:

 
while(!(cin >> x))


why is there an ! after that first (? why is it (!(cin >> x)) and not just (cin >> x)?

Then on this line:

 
cin.clear();


I know its clearing the value of x and preparing to ask the user to re-enter a value... but how exactly does IT know that? How does the code know its erasing x?

I am probably going to ask a lot of stupid questions here, but that's how we learn, right?

Thank you.
while(!(cin >> x))

The ! is negation. While cin >> x DOES NOT pass. This code basically does some rudimentary input validation. cin will fail here if you try to feed it something that it cannot cast to an int.

How does the code know its erasing x?

It doesn't know anything about x. cin is a stream object, clear() just clears the stream. You should look into the basics of streams.
http://www.cplusplus.com/reference/ios/ios/clear/

That is what you could be looking for in relation to what cin.clear(); does.
Ok, that is quite helpful.

Now what about:

 
		cin.ignore(numeric_limits<streamsize>::max(), '\n');


I realize now that I have no idea what that's doing... well I mean I know its the part that actually checks to see if the code is a number, but specifically I am confused with the stuff at the end:

 
::max(), '\n');


Why is all of that there and what is it doing?

Thanks again, I greatly appreciate the explanations.
Topic archived. No new replies allowed.