cin exception handling

G

Guest

My function use cin to get a input data, if my input is smaller enough, it
works fine; but if input a very large number ,i.e. a number out of the data
defined range, the program will go to unstable state, repeatedly print out
"Please input an interger(0 ~ 4,294,967,295): ", what should I do to catch
the exception for it?
thanks.

include <fstream>
#include <iostream>
using namespace std;

void boothRepresent(unsigned int input, char * booth);
void printBooth(char * booth, int length);

int main(int arg, char** args) {
char booth[33];
unsigned int input;

while(1) {
cout << "\nPlease input an interger(0 ~ 4,294,967,295): ";
cin >> input;
cout << endl;

if(cin) {
boothRepresent(input, booth);
cout << "Booth representation:" << endl;
printBooth(booth, 33);
}
}
return 0;
}
 
T

Tom Widmer [VC++ MVP]

maggie said:
My function use cin to get a input data, if my input is smaller enough, it
works fine; but if input a very large number ,i.e. a number out of the data
defined range, the program will go to unstable state, repeatedly print out
"Please input an interger(0 ~ 4,294,967,295): ", what should I do to catch
the exception for it?
thanks.

include <fstream>
#include <iostream>
using namespace std;

void boothRepresent(unsigned int input, char * booth);
void printBooth(char * booth, int length);

int main(int arg, char** args) {
char booth[33];
unsigned int input;

while(1) {
cout << "\nPlease input an interger(0 ~ 4,294,967,295): ";
cin >> input;
cout << endl;

if(cin) {
boothRepresent(input, booth);
cout << "Booth representation:" << endl;
printBooth(booth, 33);
}

Add here:
else
{
cout << "Invalid number entered" << endl;
cin.clear(); //clear the cin error state
}
//in any case, ignore everything else from the current line
}
return 0;
}

The above change displays an error, resets the error state on cin. Even
if an error didn't occur, the change also skips rest of the line of
input you just entered.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top