std::cin loops even if I call ignore() and clear()

前端 未结 2 1721
渐次进展
渐次进展 2021-01-22 03:38

I\'m trying to setup an input checking loop so it continuously ask the user for a valid (integer) input, but it seems to get trapped in an infinite loop.

I\'ve searched

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-22 04:19

    When the stream is in an state of error,

      cin.ignore();
    

    does not do anything. You need to call cin.clear() first before calling cin.ignore().

    Also, cin.ignore() will ignore just one character. To ignore a line of input, use:

    cin.ignore(std::numeric_limits::max(), '\n');
    

    Add

    #include 
    

    to be able to use std::numeric_limits.

    The fixed up block of code will look something like:

    int num;
    while ( !(cin >> num) ) {
       cin.clear();
       cin.ignore(std::numeric_limits::max(), '\n');
       cout << "Enter valid number: " << endl;
    }
    

提交回复
热议问题