Re: standard input question
You clear the stream state, but the "garbage" is still left in the stream. You'll need to call ignore (usually with std::streamsize's maximum value) after calling clear.
Re: standard input question
Hello Plasmator,
Thanks for your info.
I've spent a lot of time tyring to get this thing right.
but unfortunately I need more help.
if it's not too much trouble for you,
would you please show me how to do it with working sample code?
(or anyone who is willing?)
I'd really appreciate it if you could do that.
Thanks alot.
Re: standard input question
Quote:
Originally Posted by potatoCode
if it's not too much trouble for you,
would you please show me how to do it with working sample code?
Sure, basically you do this:
Code:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
This looks like a lot of noise in your client code, so wrapping it into a function might be a good idea; something along the lines of:
Code:
#include <cassert>
#include <iostream>
#include <limits>
namespace
{
std::istream& RecoverIStream(std::istream& istr)
{
istr.clear();
istr.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return istr;
}
}
int main()
{
typedef short input_type;
input_type userInput = input_type();
for(unsigned int i = 0U; i < 2U; ++i) //for illustrative purposes; query the user twice for input.
{
std::cout << "Input: " << std::flush;
if(!(std::cin >> userInput))
{
assert(false); //die in debug
}
//invoking "RecoverIStream" via [std::istream::]operator>> is also an option; i.e., "std::cin >> RecoverIStream;"
RecoverIStream(std::cin); //clear error flags and discard residual data.
}
}
Re: standard input question
Thank you plasmator.
I have yet to learn about <limits>.
The chapters I'm learning deals with I/O library,
and this question came up in my mind.
anyways, I will go dig into your sample code and come back and let you know how it went.
Thanks! :)