Why does this code that reads from cin recurse infinitely if the user types an invalid value?

Viewed 75

I am learning C++, and I wrote this code:

#include <iostream>

namespace input
{
  template <typename T>
  T prompt_user(std::string prompt)
  {
    T input;
    std::cout << prompt << ": ";
    std::cin >> input;
    if (std::cin.fail())
    {
      std::cin.clear();
      prompt_user<T>(prompt);
    }
    return input;
  }
} // namespace input

If the user types in an invalid value, my if statement would catch it with std::cin.fail() (I think that's how you do it) and start over. But it instead loops my code infinitely and skips cin. How can I fix this?

2 Answers

When you start over, you just read the same invalid value again. You have no code to figure out where the invalid value begins and ends in the input stream and remove it.

It's not clear what the fix is. What the invalid value consists of may depend on the type. Do you want to discard a line? Do you want to discard characters until you find valid input? Or what?

You need to decide what behavior you want and code it.

I had to add std::cin.ignore(std::numeric_limits<std::streamsize>, '\n') below std::cin.clear(). I am so sorry for my mess up.

Related