Search code examples
c++cin

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


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?


Solution

  • 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.