I just knew about getch() and found it better than cin (a lot) but there's one problem bugging me, can you makea n if statement for getch()?
For example they have:
But why do you think getch() is better then cin? Getch() is outdated and non-standard, so if you use it on a modern compiler, you'll get a compiler error.
Besides, comparing getch() with cin is like comparing apples with pears. They're both fruit, but the taste is quite diffrent...
Last edited by Nick Evan; Sep 4th, 2008 at 6:23 am.
>Now it somehow skips straight to 'else', missing out the 'if' and the 'else if'......
That's because getch doesn't perform text conversions. It's a straight detection of scan codes from the console. This means that on systems (such as Windows) where a newline is two values before being converted to '\n' by C++'s stream buffer, calling getch once will give you the first of those values.
Assuming you're on Windows, here's what is happening. When you press Return, a Windows newline is signaled and two values are sent to the console: 0xD and 0xA, in that order. This is the CR-LF pair you may have heard about. Let's say that '\n' in C++ represents 0xA. A standard C++ text stream will take 0xD-0xA and compact it into 0xA, but getch won't do anything of the sort and will simply return 0xD.
So the result is that you're comparing 0xD with 0xA, which is clearly not true, so the else statement is performed. You can catch the carriage return using the '\r' escape character:
Oh, wait. I put these "" instead of these '' when I tried out the code you've posted. Thanks it works fine now, but is there any reason that I should put this in?
The first line ( const int ESC = 0x1B; ) is just to improve readability. 0x1B is the ASCII code for an ESC.
Narue put the " != ESC " in the while loop, to avoid that your program enters an infinite loop. When you press ESC, getch() will pick that up and break out of the while loop.
You could replace those 2 lines by this while ( ( a = getch() ) != 0x1B) , but as you can see, it's a lot less readable that way.
Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.
This thread is more than three months old
No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.