Click to See Complete Forum and Search --> : standard input question
potatoCode
February 13th, 2008, 08:48 PM
Hello guys
I have a question about.
if a program asks the user to input a number,
but the user enters a character,
the istream is in error state, am I correct?
my question is, how do I clear it?
#include <iostream>
using namespace std;
int main()
{
short num;
cout << "Enter a number: " << endl;
cin >> num;
cin.clear();
cout << "Enter a number again: " << endl; // line A.
cin >> num;
return 0;
}
for example,
if I input numbers greater than the size of short,
line A works and waits for an input,
but if I enter any characters,
line A displays but it does not wait for the input and just exits the program.
why is that?
thanks for the help.
Plasmator
February 13th, 2008, 09:07 PM
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.
potatoCode
February 13th, 2008, 09:48 PM
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.
Plasmator
February 13th, 2008, 09:53 PM
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:
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:
#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.
}
}
potatoCode
February 13th, 2008, 10:03 PM
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! :)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.