Infinite loop with cin when typing string while a number is expected

后端 未结 4 1918
长情又很酷
长情又很酷 2020-11-22 00:35

In the following loop, if we type characters as the cin input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explai

4条回答
  •  终归单人心
    2020-11-22 01:12

    Another alternative is operator! ,it is equivalent to member function fail()

    //from Doug's answer
    if ( !cin )
    {
       cout << "ERROR -- You did not enter an integer";
    
       // get rid of failure state
       cin.clear(); 
    
       // From Eric's answer (thanks Eric)
       // discard 'bad' character(s) 
       cin.ignore(std::numeric_limits::max(), '\n');
    }
    

提交回复
热议问题