7

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

 2 years ago
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.
neoserver,ios ssh client
Calin Baenen

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;
// ...
Enter fullscreen modeExit fullscreen mode

And I discovered something interesting.
I was just playing around, and I typed 1, and spammed a bunch of 0s.
Sort of like the following.

Enter fullscreen modeExit fullscreen mode

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:

Literally only a second after I submit my answer of  raw `65536` endraw .

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";
  }
}
Enter fullscreen modeExit fullscreen mode

If anyone knows what's causing these bugs, and how I can fix them, let me know!

Thanks!
Cheers!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK