This content originally appeared on DEV Community and was authored by Calin Baenen
So, I was making hangman for fun, and I had
unsigned short guesses;
std::string word;
std::cin << guesses;
// ...
And I discovered something interesting.
I was just playing around, and I typed 1
, and spammed a bunch of 0
s.
Sort of like the following.
1000000000000000000000
And then it did something really strange, it skipped the next std::cin
command (which was the one for word
).
And then... it kept repeating, printing things over and over (probably because I was in a while(true)
), but it didn't bother to stop when it hit std::cin
, even on the next loop iteration, instead constantly having the number be equal to 65535
, (2^16)-1
; or in other words, the 16 bit integer (unsigned short
) limit.
Even if I enter 65536
, the unsigned short
limit plus one, it still bugs out in this crazy way.
Here's an image of what happens after I do this:
This is what should happen normally:
Strangely, this bug will also happen if I pass any strings that include a space () character in them for
answer
(for some reason).
This is my code:
int main() {
while(true) {
unsigned short guesses;
std::string answer;
std::cout << "Enter the amount of guesses to allow: ";
std::cin >> guesses;
std::cout << "Enter the word for P2 to guess: ";
std::cin >> answer;
std::cout << "[Guesses: " << guesses << ", " << "Word: \""
<< answer << "\"]\n";
}
}
If anyone knows what's causing these bugs, and how I can fix them, let me know!
Thanks!
Cheers!
Cheers!
This content originally appeared on DEV Community and was authored by Calin Baenen
Calin Baenen | Sciencx (2021-11-27T20:38:29+00:00) Interesting C++ bug involving `std::cin` for input.. Retrieved from https://www.scien.cx/2021/11/27/interesting-c-bug-involving-stdcin-for-input/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.