+ 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

17th Aug 2019, 3:08 AM
Charles Constantinesco
Charles Constantinesco - avatar
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/
17th Aug 2019, 3:17 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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
17th Aug 2019, 4:05 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Even if user inputs multiple characters only first character will be stored
17th Aug 2019, 6:12 AM
Alphin Davis Pomy
Alphin Davis Pomy - avatar
+ 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 ?
17th Aug 2019, 3:53 AM
Charles Constantinesco
Charles Constantinesco - avatar
+ 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
17th Aug 2019, 9:41 AM
Charles Constantinesco
Charles Constantinesco - avatar
+ 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.
18th Aug 2019, 4:35 AM
Pulkit Aggarwal
Pulkit Aggarwal - avatar
+ 1
use this int x; x = cin.get();
18th Aug 2019, 7:14 AM
Eyob
Eyob - avatar
0
~ swim ~ Yes i have fixed the problem
17th Aug 2019, 8:53 PM
Charles Constantinesco
Charles Constantinesco - avatar
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
18th Aug 2019, 4:48 AM
Cout
Cout - avatar
- 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.
17th Aug 2019, 5:33 PM
Aditya
Aditya - avatar