1

I wrote a function which shall only proceed if an int is input. If the cin fails, it shall do the do{...} while() once again until an int is input, not a char. My problem is, once I input a char, it ends up in an infinite loop. I can't tell why.

int syst ()
{
    int basisSys;
    bool opAga = false;
    do
    {
        cout << "Type the base you wanna calc. in" << endl;
        cin >> basisSys;
        if (cin.fail())
        {
            opAga = true;
        }
    }
    while (opAga == true);
    cout << endl << "You are calc. in " << basisSys << "system" << endl << endl;
    return basisSys;
}
M.K
  • 1,464
  • 2
  • 24
  • 46
Felix
  • 56
  • 1
  • 5
  • 1
    when `cin` cannot read an `int` then the characters are still in the stream. You are looing for `cin.ignore` – 463035818_is_not_an_ai Mar 01 '19 at 10:44
  • Instead of reading an `int` from the stream, read a `std::string` using (for example) `std::getline()`. Then check contents of the string to see if it contains data that would be read as an `int`. If it does, read the integral value from the string. If not, discard input, and continue. – Peter Mar 01 '19 at 10:50
  • By using the input operator `>>` you will make sure that the input is a number. Try to use it as a condition, for e.g : `while (cin >> num){//do your stuff}` – asendjasni Mar 01 '19 at 10:51

1 Answers1

1

It is important to ignore and clear the line since operator>> won't extract any data from the stream anymore as it is in a wrong format.

while(!(cin >> basisSys)){
   cout << "Bad value!";
   cin.clear();
   cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
bartop
  • 9,971
  • 1
  • 23
  • 54
vijayakm
  • 43
  • 4
  • 1
    Well that did work. But Why do I have to clear AND ignore? :) – Felix Mar 01 '19 at 11:02
  • If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need cin.clear() Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need cin.ignore – vijayakm Mar 01 '19 at 12:52