how to get a character from stdin without waiting

2019-01-24 18:09发布

问题:

This question already has an answer here:

  • How to avoid pressing enter with getchar() 10 answers

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;
}

回答1:

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;
}


回答2:

I believe there's an answer to this in the comp.lang.c fAQ. I can't load the site at the moment, but look in the "System dependencies" section.



回答3:

Since you're using ncurses, you start by calling cbreak to turn off line buffering. Then you'll call nodelay to tell it not to wait before returning -- getch will always return immediately. When it does, you'll check whether a key was pressed, and if so what key that was (and react appropriately).



标签: c ncurses curses