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

Aug 2, 2011 at 7:27pm
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 Aug 2, 2011 at 7:27pm
Aug 2, 2011 at 8:17pm
hey man you cant read \n or enter or space with cin !!!
you must use cin.get
Aug 2, 2011 at 8:18pm
use
1
2
3
4
5
a = cin.get();

or 

cin.get( a ); // its better becuase a is type of char 
Last edited on Aug 2, 2011 at 8:19pm
Aug 2, 2011 at 8:22pm
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.
Aug 3, 2011 at 12:59pm
yes operator >> ignore all of enter and space !! and you cant read with this
Aug 3, 2011 at 2:39pm
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;
Aug 3, 2011 at 2:47pm
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.