Move the cursor in a C program

后端 未结 4 1887
Happy的楠姐
Happy的楠姐 2020-12-14 18:01

I\'d like to move the cursor forward and backwards in a C program. I\'m reading the whole line in a loop, but i would like that if a cursor key gets pressed the cursor on th

4条回答
  •  情话喂你
    2020-12-14 19:00

    A simple example using ANSI escape sequences:

    #include 
    
    
    int main()
    {
        char *string = "this is a string";
        char input[1024] = { 0 };
        printf("%s", string);
        /* move the cursor back 5 spaces */
        printf("\033[D");
        printf("\033[D");
        printf("\033[D");
        printf("\033[D");
        printf("\033[D");
        fgets(input, 1024, stdin);
        return 0;
    }
    

    To do very much useful the terminal needs to be put into canonical mode with termios.h and/or curses.h/ncurses.h. This way the backspace key code can be caught and responded to immediately and the buffer drawn to screen accordingly. Here is an example of how to set the terminal into canonical mode with tcsetattr():

    struct termios info;
    tcgetattr(0, &info);
    info.c_lflag &= ~ICANON;
    info.c_cc[VMIN] = 1;
    info.c_cc[VTIME] = 0;
    tcsetattr(0, TCSANOW, &info);
    

    Another option might be to use the readline() or editline() library. To use the readline library specify -lreadline to your compiler. The following code snippet can be compiled with

    cc -lreadline some.c -o some
    
    
    #include 
    
    #include 
    #include 
    
    int main()
    {
        char *inpt;
        int i = 0;
    
        while ( i < 10 )
        {
            inpt = readline("Enter text: ");
            add_history(inpt);
            printf("%s", inpt);
            printf("\n");
            ++i;
        }
        return 0;
    

    }

提交回复
热议问题