简体   繁体   English

如何在C ++控制台应用程序中控制光标位置?

[英]How to control a cursor position in c++ console application?

I'm supposed to create a console application for school project and it's about Sudoku Game, so the thing is i don't find any struggle with the algorithm, but i was wondering if i could draw the full Sodoku table with c++ and make empty squares as "data" input place so the user can move the cursor using the arrow keys to the specific number's place to fill it with the appropriate number. 我应该为学校项目创建一个控制台应用程序,并且它是关于Sudoku Game的,所以事情是我在算法上没有发现任何困难,但是我想知道是否可以使用c ++绘制完整的Sodoku表并清空正方形作为“数据”输入位置,因此用户可以使用箭头键将光标移动到特定数字的位置,以用适当的数字填充它。 is there a method to do it this way ? 有没有办法做到这一点?

In windows you should use windows api. 在Windows中,您应该使用Windows API。

from there, use SetCursorPos() for it. 从那里,使用SetCursorPos()

Look at ncurses library for creating text-based user interfaces. 查看用于创建基于文本的用户界面的ncurses库。 It works fine with Linux and with Windows under Cygwin/MinGW. 它可以在Linux和Cygwin / MinGW下的Windows下正常工作。

It depends on your OS/Compiler. 这取决于您的OS /编译器。 For example, in VC++ you can use this and example can be found here . 例如,在VC ++中,您可以使用它,并且可以在此处找到示例。

#include <windows.h>
int main(){
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos = {3, 6};
SetConsoleCursorPosition(hConsole, pos);
WriteConsole(hConsole, "Hello", 5, NULL, NULL);
return 0;
}

If you want to do it in Linux with g++ compiler, you can use special libraries such as curses or write your own implementation(will be a bit difficult). 如果要使用g ++编译器在Linux中进行操作,则可以使用特殊的库(例如curses)或编写自己的实现(这会有些困难)。 Such for just placing the cursor at the required position, you can use this: 例如,仅将光标放在所需位置,可以使用以下命令:

void gotoxy(int x,int y)    
{
    printf("%c[%d;%df",0x1B,y,x);
}
void clrscr(void)
{
    system("clear");
}
int main() {    
    int x=10, y=20;
    clrscr();
    gotoxy(x,y);
    printf("Hello World!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM