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

前提是你 提交于 2021-02-19 09:12:46

问题


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. is there a method to do it this way ?


回答1:


It depends on your OS/Compiler. For example, in VC++ you can use this and example can be found here.

#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). 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!");
}



回答2:


Look at ncurses library for creating text-based user interfaces. It works fine with Linux and with Windows under Cygwin/MinGW.




回答3:


In windows you should use windows api.

from there, use SetCursorPos() for it.



来源:https://stackoverflow.com/questions/54250401/how-to-control-a-cursor-position-in-c-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!