-
Error-handling code
Hey everyone, I have some more questions for the community :)...I promise when I learn enough I will pass my knowledge to every human being in my path of programming destruction! haha everyone here's been (and hopefully will continue to be ;)) disturbingly helpful...that's right! I went there! So anyways, now that the ranting and raving's outta the way...here's the code and following is the QUESTION! bum bum bum:
Code:
if (!cin) //bad input
{
cin.clear();
while (cin.get() != '\n')
continue;
cout << "Bad input; input process terminated.\n";
break;
}
The question here is what exactly does the
while (cin.get() != '\n')
continue;
section do? Does it help in the removal of the bad input? As much information on this subject as well as what the continue in there does...and if you feel like discussing the entire chunk of code...by all means, that would be even greater, I didn't want to be too much of a hassle...hey if anyone's getting any help from my questions other than me, speak up...I feel like the annoying little brother who keeps jumping up and down begging for programing attention hahaha...alright, thanks everyone :) -Chap
-
im pretty new to thsi stuff to, and would be useful, but
as far as i know, this chunk code seems to means to me
if the input is bad, it clears all of the input so far
then it runs a while statment which reads characters until the
character is '\n', which is a new line, or when you press enter,
however you look at it.
then if all is good it continues to the next segment of code, if
something is wrong, then it displays the cout segment
which tells you on screen there is an error, and then break
ends the program or that section of code im not to sure, but
that basic of what that does i believe, feel free to correct me
cause ive onyl been programming on a regular basis for a little
while.
-
right wher you have it is fine. but keyword continue isn't necessary and since the loop will have ended by the time you have keyword break, that isn't necessary either. Also what happens if the user hits the enter key repeatedly, but no other key? Probably better to be sure you clear the input buffer using something like this:
Code:
if(!cin)
{
cin.clear();
cin. ignore(std::numeric_limits<std::streamsize>::max())
cout << "bad input" << endl;
}
-
right - 'flushing' cin's input buffer to prepare it for the next input event.
>> as well as what the continue in there does
'continue' causes execution to jump back to the beginning of the loop, bypassing any code that follows, ie:
Code:
while(1) {
cout << "blah" << endl;
continue;
cout << "this will never print" << endl;
}
-
I've always used
cin.ignore(cin.rdbuf()->in_avail());
to clear cin. This ensures that the clearing operation will not block and that everything that's there gets removed.