2013-01-18 81 views
1

我使用Visual Studio 2010和我想移动光标时,键盘上的用户按右键数组键:c + +移动光标在控制台

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

using namespace std; 

void gotoxy(int x, int y) 
{ 
    static HANDLE h = NULL; 
    if(!h) 
    h = GetStdHandle(STD_OUTPUT_HANDLE); 
    COORD c = { x, y }; 
    SetConsoleCursorPosition(h,c); 
} 

int main() 
{ 
    int Keys; 
    int poz_x = 1; 
    int poz_y = 1; 
    gotoxy(poz_x,poz_y); 

    while(true) 
    { 
     fflush(stdin); 
     Keys = getch(); 
     if (Keys == 77) 
       gotoxy(poz_x+1,poz_y); 
    } 

    cin.get(); 
    return 0; 
} 

它的工作,但只有一次 - 第二,第三等按下不工作。

+0

'fflush(stdin);' - 不这样做。我不想忍受由于代码中的一行而自发燃烧的可能性。 – chris

回答

0

你永远不会改变poz_x,所以你总是最终调用

gotoxy(2,1); 
在循环

3

您永远不会在您的代码中更改poz_x。在你的while循环中,你总是移动到初始值+1。像这样的代码应该是正确的:

while(true) 
{ 
    Keys = getch(); 
    if (Keys == 77) 
    { 
      poz_x+=1;  
      gotoxy(poz_x,poz_y); 
    } 
} 
+0

谢谢,现在工作:) –