[C++] Need help with cin input

Sup there

So i’m having a problem with cin input :

char t;
cout << "It's your turn (you have " << tries << " tries left): ";
cin >> t;

Problem is that the user is able to input more than 1 character on the console even tho it’s a “char” type and my program keep looping like if he put “test” in the input it gonna loop 4 times. But that’s not what i want. I want it to only get the first char from the input.

How i can limit the cin input on the program ?


You can’t limit the input. (How would you do that, unplug the keyboard, hit the user over their head?) But you can ignore it. Clear the buffer.
Or if as you say you want only the first character, then don’t do it on a loop. Read one character, and not any more.

Maybe all you’re really looking for is: read the whole line. This is easier than figuring out how much input is queued up so if you don’t care beyond that, then look no further. It’s quite likely that you don’t have any need for anything else, because when you see a linebreak then you know you’re in sync (because the user probably types a whole lot slower than you process the input, they won’t have had time to press another key) with the user because the input is line buffered, it’s flushed every time a line ends, the de-sync comes from when the user is typing before having ended the line. Another alternative is to change the buffering mode so that you’re in sync with every key press, but, again, you can’t limit the input, there can always be purposefully badly formed input.

1 Like

To get you the point here is the project : https://github.com/CharlesCpp/Hanged-Man

On thehangedman.cpp
If you compile the program and start it you would be able to input multiple char when asking for the user input once the game started. But i find no way to control that.


While it would be really cool if you could write code that would unplug the keyboard, and hit the user over the head for intentionally not following instructions as @ionatan suggested :rofl: , another solution might be to require a single character through code. For example:

#include <iostream>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main() {
  string letter;
  while (letter.length() != 1)
    cout << endl << "Type a single letter and press <enter>: ";
    cin >> letter;
  cout << endl << "You chose: " << letter << endl;
  return 0;

Basically just write a function to validate the input before continuing on.


I’ll just repeat myself.

You cannot prevent the user from typing.
But you can ignore what they type.

You probably mean the second, but you’re expressing it in terms of the first, and trying to write code for that is not possible. Writing code for the second one is very possible. Read the input, and don’t do anything with it. Or change the buffering mode. Pretty sure I already covered it all, not even sure why I’m typing this in >.>