how should i write a syntax which diagnosis that user press enter or space?

in c++ when user press enter or press space i want to do defferent orders.for example when user press enter it prints "you press enter" and when press space it prints "you press space".i think it should be like this code :
1
2
3
4
5
6
7
8
char a;
cin>>a;
if(a=='\n')
cout<<"you pressed enter";
else if(a==' ')
cout<<"you pressed space";
else
cout<<"you pressed another click";

i use these syntax but it doesn't work and it doesent do anything when i press enter.how can i do this.please show me the correct codes.
Last edited on
hey man you cant read \n or enter or space with cin !!!
you must use cin.get
use
1
2
3
4
5
a = cin.get();

or 

cin.get( a ); // its better becuase a is type of char 
Last edited on
As far as I know, when you use std::cin, the program waits for the user to enter a character, so if you just press enter without typing anything in, it will continue to wait for the user's input.
yes operator >> ignore all of enter and space !! and you cant read with this
i find out what is the working code:

#include <iostream.h>
#include <conio.h>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void main()
{
char a;
a=getch();
switch(a)
{
case '\r':
cout<<"Enter pressed";
break;
case '\n':
cout<<"Enter pressed";
break;
case ' ':
cout<<"Space Pressed";
break;
default:
cout<<"Other Key Pressed";
break;
}
getch();
}


but i didn't understand what is the use of this part??
1
2
3
case '\n':
cout<<"Enter pressed";
break;
What don't you understand, the switch construct? or the fact that two different chars are associated with the ENTER key?

The fact that two different chars area associated with ENTER is because operating systems interpret this key diferently. you can read about it here:

http://en.wikipedia.org/wiki/Enter_key

Topic archived. No new replies allowed.