Question

I have made a little program where I can move the cursor up,down,left and right.

now the last thing I want to add is the ability for the cursor to jump to the next or previous if it gets to the edge of the screen.

since I already implemented all kinds of checks to make sure I can move up and down within the key_up and key_down input handle parts I would like to 'borrow' these. I could of course rewrite them and reuse them in the key_left and key_right scenarios.

However it would be way shorter if I could just write to stdin and 'fake' user input as if key_up or key_down was pressed, and only have to change the x-position of the cursor.

so what I want something like this

putc(KEY_UP,stdin);fseek(stdin,-1, SEEK_CUR);

so on the next getch() it retrieves the character I put to stdin with putc!

I use ncurses for the entire program interface!

on Filipe suggestion I tried to do something with ungetc(), but it doesn't have the behavior I want.

here is a small test program, in theory it should print out infinite p's after the first character but it doesn't:

#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>

int main () {
    int       input,i=0;

    initscr();
    start_color();
    keypad(stdscr, TRUE);
    raw();
    nonl();
    noecho();

    do {
        input=getch();
        if (i==24) {i=0;erase();}
        mvprintw(i,0,"%c --- %i",input,input);
        refresh();
        if (ungetc((unsigned char)'p', stdin)==EOF) {
            printw("    ERROR UNGETC");
        }
        else {printw("    SUCCES UNGETC");}
        ++i;
    } while (input!='q');
    endwin();
    exit(2);
}
Was it helpful?

Solution

Since you're using ncurses, you're looking for ungetch(). From the manpage:

The ungetch routine places ch back onto the input queue to be returned by the next call to wgetch. There is just one input queue for all windows.

The function prototype:

int ungetch(int ch);

It returns the integer ERR upon failure and an integer value other than ERR (OK in the case of ungetch()) upon successful completion.

For future reference only

If anyone reading this answer wants a simple way to push back characters onto a file stream, ungetc() is the correct approach. ungetch() is appropriate only for anyone using ncurses.

ungetc() pushes back one character into a given file stream:

int ungetc(int c, FILE *stream);

From the manpage:

ungetc() pushes c back to stream, cast to unsigned char, where it is available for subsequent read operations. Pushed-back characters will be returned in reverse order; only one pushback is guaranteed.

You will want to call it with stdin, as in:

ungetc((unsigned char) KEY_UP, stdin);

It returns c on success, EOF on error. Bear in mind that it only guarantees one push back character; you can't call ungetc() twice and then expect that calling getch() twice gives you back the last 2 pushed characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top