cin exception handling

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • maggie

    #1

    cin exception handling

    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(boot h, 33);
    }
    }
    return 0;
    }


  • Tom Widmer [VC++ MVP]

    #2
    Re: cin exception handling

    maggie wrote:[color=blue]
    > 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(boot h, 33);
    > }[/color]

    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
    cin.ignore(std: :numeric_limits <std::streamsiz e>::max(), '\n');

    [color=blue]
    > }
    > return 0;
    > }[/color]

    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

    Comment

    Working...