2014-10-12 78 views
1

我所限定的四个箭头键作为such-检测为双方向上和向右C++,向上箭头

#define UP_ARROW 72 
#define LEFT_ARROW 75 
#define DOWN_ARROW 80 
#define RIGHT_ARROW 77 

并且键正在使用_getch()检查,因为这样的

char key = _getch(); 
if (key == 0 || key == -32) 
{ 
    key = _getch(); 
    switch (key) 
    { 
    case UP_ARROW: 
     //These are functions not relevant to the problem 
     //up(1); 
    case DOWN_ARROW: 
     //down(1); 
    case LEFT_ARROW: 
     //left(1); 
    case RIGHT_ARROW: 
     //right(1); 

     //Pressing up will print out "test", which should not happen 
     printf("test"); 
    } 
} 

作为评论说,按下会在RIGHT_ARROW情况下调用任何东西。我做错什么了吗?

回答

4

您需要一个break;语句来停止开关的继续。

可以使用break语句结束switch语句中的特定情况 的处理,并跳转到开关 语句的结束。如果没有中断,程序会继续执行下一个案例, 执行语句,直到到达中断或语句结束为 。在某些情况下,这种延续可能是可取的。

http://msdn.microsoft.com/en-us/library/66k51h7a.aspx

3

没有break,该case语句运行所有通过:

case UP_ARROW: 
    //up(1); 
    break;  //here 
case DOWN_ARROW: 
    //down(1); 
    break;  //and here 
3

我曾经用它作为: -

#include <stdio.h> 
#include <conio.h> 

#define KB_UP 72 
#define KB_DOWN 80 
#define KB_LEFT 75 
#define KB_RIGHT 77 
#define KB_ESCAPE 27 


int main() 
{ 
    int KB_code=0; 

    while(KB_code != KB_ESCAPE) 
    { 
    if (kbhit()) 
     { 
      KB_code = getch(); 
      printf("KB_code = %i \n",KB_code); 

      switch (KB_code) 
      { 
       case KB_LEFT: 
          //Do something 
       break; 

       case KB_RIGHT: 
          //Do something      
       break; 

       case KB_UP: 
          //Do something      
       break; 

       case KB_DOWN: 
          //Do something      
       break; 

      }   

     } 
    } 

    return 0; 
} 
相关问题