Interesting C++ bug involving `std::cin` for input.
source link: https://dev.to/baenencalin/interesting-c-bug-involving-stdcin-for-input-14gg
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Posted on Nov 27
Interesting C++ bug involving `std::cin` for input.
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.
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!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK