c·c++/c++ 프로그래밍

cin을 이용하여 정수를 안전하게 입력받기.

바로이순간 2011. 12. 3. 13:34

#include <iostream>
#include <limits>

 

using namespace std;
int main() {  
    int num1;

 

    cout<<"\nEnter first number:\n";
    cin>>num1;

    while(!cin.good()) { //this means while input is not valid, do this.
                         // if input is valid, this code will not execute
        cin.clear();     //clear the error state

 

        //ignore all characters left in the buffer
        cin.ignore(numeric_limits<streamsize>::max(),'\n');

 

        //let the user know it was wrong
        cout<<"That is not a valid number. Try again.\n";

 

        //let them enter the number again if it was not good, and it will check again
        cin>>num1;

 

        //if input is good, it will exit the loop and go on to the next step
    }

    cout<<num1<<endl;

    return 0;
}