How to fix unwanted curses output indenting

时间:2019-04-08 13:36:31

标签: c linux curses

Continuous input code with arrow keys. Why is output repeatedly indented?

I'm writing on C using the lncurses library. I need to get continuous input with the arrow keys but my output is all weird and intended. I tried swapping \n with \r, but then it doesn't output anything at all even tho its registering key presses.

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <curses.h>

#include <pthread.h>

void *input(void *arg)
{
printf("Thread running\r\n");
int ch = 0;

while(1)
{
    ch = getch();
    switch(ch)
    {
        case KEY_UP : 
            printf("up\n");
            break;
        case KEY_DOWN :
            printf("down\r");
            break;
        case KEY_LEFT :
            printf("left\r");
            break;
        case KEY_RIGHT:
            printf("right\r");
            break;
    }

}
return NULL;
}


void initcurses(); 
int main(int argc, char *argv[])
{
    //Initialise ncurses library functions
    initcurses();

    pthread_t t_input;
    pthread_create(&t_input, NULL, input, NULL);
    pthread_join(t_input, NULL);
}

void initcurses()
{
    //Initialise library
    initscr();
    //Enable control characters
    cbreak();
    //Disable getch echoing
    noecho();
    //Flush terminal buffer
    intrflush(stdscr, TRUE);
    //Enable arrow keys
    keypad(stdscr, TRUE);
}

I expect to see which key is pressed on a new line every time. Instead they are indented.

The code should be enough to reproduce the result. Compile with cc -pthread -o file file.c -lncurses

Also some notes: KEY_UP is the only thing that will have any output due to the \n character? Any other keys will be printed after UP has been pressed after them.

1 个答案:

答案 0 :(得分:0)

As @Groo pointed out, the program was doing what I told it to do.

Using \n made a new line exactly after the output so it needed a \r carriage return to properly start it from the beginning.

Swapping \n or \r to \n\r has the desired effect.