While loop with try catch fails at bad cin input

后端 未结 6 1944
耶瑟儿~
耶瑟儿~ 2020-12-11 09:05

I can\'t seem to figure out why this falls into a loop after getting non-int input. I\'ve tried cin.flush(), which doesn\'t seem to exist, cin.clear(), which seems like it s

6条回答
  •  眼角桃花
    2020-12-11 09:58

    My Problem was to block char input to a cin >> number

    This error caused an 'infinite' loop showing my prompt cout << prompt with no way of exit but kill the process ...

    The following shows what worked for me!

    ========================================

    double fi_trap_d()    // function to return a valid range double catching errors  
    {  
      double fi_game_sec;  
    //-------------------------------------------  
       do  
       {  
        fi_game_sec = -1;  
        cout << fi_game_sec_c;  
    
            //------------------------------  
        cin.ignore();  // (1)
            //------------------------------  
    
        try  
        {  cin >> fi_game_sec;  cin.clear(); }  // (2)
            catch (...)  //out_of_range)  
          {  
            fi_game_sec = -1;  
            cout << " Dis am an error!\n";  
                         // just loop back as we asked for a number  
          }  
        } while (fi_game_sec < 1);  
    //-------------------------------------------  
      return fi_game_sec;  
    }  
    

    ========================================

    Despite trying the " Dis am an error! " has NEVER shown up.

    The key was (1) & (2) !

提交回复
热议问题