Do-while endlessly looping cout, ignores cin

后端 未结 2 2097
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 01:21

This program prints a specified amount of numbers within a specified range. However, when I enter a character, it just endlessly loops whichever do-while loop I do it in. E.

2条回答
  •  余生分开走
    2021-01-15 01:58

    You could try doing something like

    int a;
    string trash;
    
    do {
      cout << "Enter minimum number" << endl;
      cin >> a;
    
      if(cin.fail()){
        cin.clear();
        cin >> trash;
      }
    
    } while (cin.fail());
    

    This will remove any bad input from the cin stream by throwing it into the trash string.

    This link may help you understand these cin functions a bit better.

    http://web.eecs.utk.edu/~cs102/lectures/cinLecture.html

提交回复
热议问题