How to make cin take only numbers

后端 未结 4 1090
青春惊慌失措
青春惊慌失措 2020-11-22 07:30

Here is the code

double enter_number()
{
  double number;
  while(1)
  {

        cin>>number;
        if(cin.fail())
        {
            cin.clear()         


        
4条回答
  •  無奈伤痛
    2020-11-22 07:59

    I would prefer the following code. Among many codes to clear this question out of our minds, I think this is most appropriate code I found online.

    #include 
    #include 
    using namespace std;
    
    int main(){
        int n;
        while(!(cin >> n)) {
            cin.clear(); // to clear the buffer memory
            cin.ignore(numeric_limits::max(), '\n');
            cout << "Please enter a valid integer!";
        }
        cout << "Your Integer: " << n << endl;
        return 0;
    }
    

提交回复
热议问题