+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

c++

8/17/2019 3:08:12 AM

Charles C

14 Answers

New Answer

+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

+3

Charles C Don't have a laptop or pc. But i tried by combining all three files in on CxxDroid and there was an immediate crash. Then i saw the code, i don't know how it is working at your end. char* mot is uninitialized you are allocating memory for it by first calling lenght(mot), inside lenght function, the program will crash at first dereference (indexing) while(str[i]) itself.

+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 ?

+2

Charles C If you want to read only 1 char and ignore others then you can read it using cin.get() function get reads one char at time char c = cin.get(); or char c; cin.get(c)

+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

Charles C It seems to work fine at my side. Can you provide sample input that is causing an issue. Also let me know the expected output for a given input.

+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.

-1

char t[1]