Public Group

# Few problems with console input

This topic is 3078 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am creating a small text based RPG game. It's all going well although im running into a few bugs which are starting to become quite annoying. 1. If users press buttons while story text is up, what they typed shows up in the input space when they are prompted. 2.If people input strings when they are asked for numbers, The console produces some very wierd results. Would somebody explain some possible way to overcome these annoying bugs. Any help or advice is greatly appreiciated.

##### Share on other sites
What functions do you use?

For the first one: key presses are buffered. So even if your program halts for second, it receives key presses, which are buffered (so they don't "get lost").

If you do want to lose them, you have to "swallow" them:

you can do something like this (sorry, I coded for DOS)
while( kbhit() )//key was pressed; more precisely: the keyboard buffer is not empty    getch();//read key (more precisely remove character from the buffer)    //note, simply you don't use its return value
This way you can remove all the keypresses, if you want to.

You can put it just before requesting the input:
while( kbhit() )      getch();getline();//or whatever you use for user input

For the second, you will get better advices than I would give you.

##### Share on other sites
Thank you for your response, I will give it a try.

##### Share on other sites
szecs covered conio.h, which you may not be using. If you're using istream (ie. std::cin) you'll want to use cin.ignore(). You can use that to clear characters from the buffer just prior to displaying a prompt. By default it skips 1 character so you'll want to specify a suitably large number you think nobody would type more than. For your second question you'll want to look at cin.fail(). You can use that to check for bad input. Note that the bad input remains in the buffer and you'll have to use ignore again to clear it. You'll also need to clear the fail bit with cin.clear() to tell it you've fixed the problem. Also note that the variable you attempted to set is not set if it fails. That is why you got weird output if you tried to display an uninitialized variable. You might want to set it to some default value like 0 first.

1. 1
2. 2
3. 3
Rutin
22
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 10
• 12
• ### Forum Statistics

• Total Topics
632569
• Total Posts
3007121

×