Detecting Enter and ESC in C++ with ASCII code


Hello,

How can I detecting Enter and ESC in C++ with ASCII code?
I put one breakpoint in the (int)ch != 27
When I press enter key I saw char is 3 instead 13.

Thanks in advance


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
    srand(time(NULL));
    char ch = '13';
    int face = 0, back = 0;
    do{
        cout << "The coin was thrown\n";
           if (rand() % 2 == 0)
           {
               face++;
           }
           else
               back++;

           cout << "Press ENTER to continue... or ESC to exit ";
    } while ((int)ch != 27);

    cout << "Face: " << face << endl;
    cout << "Back: " << back;

    return 0;
}



'enter' varies by system, its a mix of 10 and 13 ascii codes (or both, on windows 'text' files).
escape may also not be easy to detect. If you look at the ascii table, there isn't an escape: there is no such key :) Ive only used escape using window's virtual key (it has an escape there) traps. To detect it with getch or something, you need to 1) get the keyboard input and 2) print the numeric value on screen to see what to look for. And it may not be consistent across OS / platforms.

c++ headers are <cstdlib> and <ctime>; mixing C's headers into C++ code can break things in larger projects due to namespace problems.

<random> is the C++ tool for random numbers. rand etc is C.

your code does not modify ch, so it will never be 27. You need a cin or something?
detecting these kinds of things in pure c++ console programs is a lot of trouble: perhaps a KISS approach of press 'q' to quit is in order here? Remember that cin will give trouble with reading blank end of lines and escape may not provide anything that can be read by any normal means (it may trigger an interrupt without data, I forget exactly how it works).

do not cast char to int. char is already a type of int and compares to 27 without a cast just fine. A smart compiler will ignore you, a dim one might waste time upcasting the registers which may affect performance. The only time you need to cast is in a print statement, which will default to printing the ascii value instead of numeric if not told to do it as a number.

char ch = '13'; this is not right ... its 2 chars in a char variable. (It is legal, there is a name for it, but its an exotic syntax that you did not intend).
you mean ch = 13; //the integer value.
Last edited on
Topic archived. No new replies allowed.