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>
intmain(){while(true){unsignedshortguesses;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';}}}
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Obviously, 65536 can't fit in an
unsigned short
and the convertion fails. cppreference explains why you get 65535:You should call
fail()
to check whether the conversion has been sucessful. You can also test the stream withoperator!()
.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: