Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems with getch()

Status
Not open for further replies.

WarrenB

Programmer
Feb 7, 2001
38
GB
Basically my problem is as follows. I ahve a piece of code like so:

cout << &quot;Please make your selection:\n1. Encrypt Code\n2. Decrypt Code\n3.Exit\n\n&quot;;
menuchoice = getch();

however the program goes to get the character before displaying the contents of the menu. How do I resolve this problem? Thanks in advance.
Warren Brown
wazzer@btinternet.com
 
Please try the following code. I think the &quot;endl&quot; is the key:

cout << &quot;Please make your selection:\n1. Encrypt Code\n2. Decrypt Code\n3. Exit\n&quot;<<endl;
menuchoice = getch( );
menuchoice -= '0'; // convert ASCII character code to number
 
Well, I don't think that is exactly correct. The problem is, the output is buffered, so it is not immediately outputed when you call cout. This is what is happening. You need to flush the buffer before you ask for input, this will guarantee that you get stuff in the right order. Endl may flush the buffer, I don't know, but it's not the root of your problem. Endl prints a newline, for sure, so you only need the '\n' or the endl, not both. If endl does flush the buffer, use it, otherwise, find the function that does flush it and call that before getch(). Alternativly, but not correctly, cerr is not buffered and if you used that instead of cout you would get the desired effect without using flushing.

Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
 
I must admit that when I wrote the first reply, I didn't know why endl worked -- only that it did. However, it does flush the buffer. See


and


Once again I speak with only limited knowledge -- so double check me on this -- but the following direct call to the flush function also seems to work:

cout.flush( );
 
Hi,
what I would suggest to cout.flush() is similar call i.e. _flushall(), coz there may be problem with other stream buffers too. One just can't say that the problem may exist with cout or output being buffered. _flushall() flushes all streams and clears the buffer. So that might help ur case. Try this out if cout.flush() doesn't work.
Thanks and regards,
Hemant Kapadia.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top