DEV Community

Discussion on: Interesting C++ bug involving `std::cin` for input.

Collapse
 
pgradot profile image
Pierre Gradot

Obviously, 65536 can't fit in an unsigned short and the convertion fails. cppreference explains why you get 65535:

For unsigned integers, if extraction results in the value too large or too small to fit in value, std::numeric_limits<T>::max() is written and failbit flag is set.

You should call fail() to check whether the conversion has been sucessful. You can also test the stream with operator!().

If the conversion has failed, you should clear() the error state flags. You should also empty the input buffer, otherwise the next iteration of the loop will run into the same bad convertion [repeat while true].

The code may then looks like:

#include <iostream>

int main() {
  while (true) {
    unsigned short guesses;
    std::cout << "Enter the amount of guesses to allow: ";
    std::cin >> guesses;

    if (std::cin.fail()) {
      std::cout << "Conversion failed" << '\n';
      std::cin.clear();
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    } else {
      std::cout << "You have entered: " << guesses << '\n';
    }
  }
}
Enter fullscreen mode Exit fullscreen mode