how to get a character from stdin without waiting for user to put it?

23,361

ncurses has the capability to do this through it's own getch() function. See this page

#include <curses.h>

int main(void) {
  initscr();
  timeout(-1);
  int c = getch();
  endwin();
  printf ("%d %c\n", c, c);
  return 0;
}
Share:
23,361
sorush-r
Author by

sorush-r

C/C++ Linux development Embedded Systems Electronics Hobbyist And I Love cats :&gt;

Updated on July 09, 2022

Comments

  • sorush-r
    sorush-r almost 2 years

    I'm writing a C program that prints something on terminal using ncurses. It should stop printing when user press 's' and continue again when press 's'. How can I read a key from input without waiting user to press the key?

    I tried getch() and getchar() but they wait until a key is pressed...

    Edit

    This is my code:

    int main(void)
    {
       initscr(); /* Start curses mode         */
       refresh(); /* Print it on to the real screen */
       int i = 0, j = 0;
       int state = 0;
       while (1)
       {
          cbreak();
          int c = getch(); /* Wait for user input */
          switch (c)
          {
             case 'q':
                endwin();
                return 0;
             case 'c':
                state = 1;
                break;
             case 's':
                state = 0;
                break;
             default:
                state = 1;
                break;
          }
          if(state)
          {
             move(i, j);
             i++;
             j++;
             printf("a");
             refresh();
          }
       }
       nocbreak();
       return 0;
    }
    

    EDIT 2 This works well. I got 100 points :)

    #include <stdio.h>
    #include <stdlib.h>
    #include <curses.h>
    
    int main(void)
    {
       initscr();
       noecho();
       cbreak();         // don't interrupt for user input
       timeout(500);     // wait 500ms for key press
       int c = 0;        // command: [c|q|s]
       int s = 1;        // state: 1= print, 0= don't print ;-)
       int i = 0, j = 0;
       while (c != 'q')
       {
          int c = getch();
          switch (c)
          {
             case 'q':
                endwin();
                return 0;
             case 'c':
                s = 1;
                break;
             case 's':
                s = 0;
                break;
             default:
                break;
          }
          if (s)
          {
             move(i, j);
             printw("a");
             i++;
             j++;
          }
       }
       endwin();
       nocbreak();
       return 0;
    }