Esc and switch

I'm trying to catch the Esc key but I don't know how to do that
So here is my code describing what I want to do

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include<stdio.h>
using namespace std;
int main()
{
    cout<<"enter character or press Esc "<<endl;
    switch(cin.get())
    {
    case'1': //call to function 1
        break;
    case'2'://call to function 2
        break;
    case 'Escape key pressed':call to function 3//I don't know how to do this
        break;
    default:cout<<"Error"<<endl;
    }
}


Help me please
Thanks
First, cin.get() won't get you anywhere with this. You can pull it off by using getch() (part of conio.h) and testing its ASCII value accordingly. Take note that this isn't standard.

1
2
3
4
5
6
	key = getch();

	switch(key) {
		//...
		case 27: function() // ascii char code for ESC
	}

Last edited on
@Baso
Expanding on what cantide5ga wrote, here is a full program using the idea. Pressing ESC ends the program.
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// ESC key.cpp : main project file.

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <conio.h>

using namespace std;
int Function1(int func1)
{
	func1++;
	return func1;
}

int Function2(int func2)
{
	func2++;
	return func2;
}

int main()
{
	char key;
	int call1=0,call2=0;
	do
	{
		cout<<"enter character or press Esc "<<endl;
		key = getch();
		switch(key)
		{
		case 49: //call to function 1
			{
				call1 = Function1(call1);
				cout << "call1 = " << call1 << endl;
				break;
			}
		case 50://call to function 2
			{
				call2 = Function1(call2);
				cout << "call2 = " << call2 << endl;
				break;
			}
		case 27:// call to function 3//I don't know how to do this
			{
				cout << "ESC key pressed..\nEnding program.." << endl << endl;
				break;
			}
		default:
			cout<<"** Error ** Only a 1, 2 or ESC key recognized.." << endl << endl;
		}
	}while (key!=27);
}
@ cantide5ga && @ whitenite1

Thanks so much guys that solves the problem.
:)
Topic archived. No new replies allowed.