+ 5
[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. How i can limit the cin input on the program ? Thanks
14 Réponses
+ 8
You can't.
What you can do, is to validate the input and remove any remaining characters in the input stream so that they do not interfere with other cin statements. This is done via a call to cin.ignore right after the cin statement to t.
http://www.cplusplus.com/reference/istream/istream/ignore/
+ 8
Charles C
Try to input multiple characters, with and without the cin.ignore line. Observe what happens when a and b are printed.
https://code.sololearn.com/cpKc90gN82Ah/?ref=app
+ 3
Even if user inputs multiple characters only first character will be stored
+ 2
Hatsy Rei
Thanks for replies !
Well i have tried that cin.ignore but doesn't seems to work. Maybe i have the bad syntax but i can't find any good exemple on google.
You have any idea how i can syntax the cin.ignore to ignore all but the first char ?
+ 1
I know right that only 1 char will be stored but well here is the project :
https://github.com/CharlesCpp/Hanged-Man
If you compile and try run it, once you put the word you want to find, once you input a char after you can output more than 1 char it will loop the size of all char for some reason
+ 1
Actually, there isn't any way to put limit because it will continue reading input unless you hit enter key and if you entered more characters than limit (in this case is 1) then it will cause runtime error.
+ 1
use this
int x;
x = cin.get();
0
~ swim ~ Yes i have fixed the problem
0
Make it as a string and check the length... Or use ignore becides Why do you care that he can enter more than 1 character it's not like you are going to publish it to something
- 1
Well the fact is some compilers don't allow entry of character response in the middle of a program, To solve this problem the character response should be entered at the start of program.