In c, how can I make a scanf function that does not require the user to press Enter?

I am trying to create a program that asks the user to write 4 numbers, and after these 4 numbers the program will accept these numbers without pressing the "Enter" button. I tried to use the scanf () function, but scanf () requires the user to press Enter. Does anyone know how I can do this?

+4
source share
3 answers

On UNIX, to control the return of data from a terminal device, you use the tcsetattr () / tcgetattr () functions to change the characteristics of the terminal device. Apparently, these functions are also POSIX.2001.

C, , , (. , ):

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>

int main(int argc, char * argv[]) {
  int i[4] = {0};
  struct termios oldtermios, newtermios;
  tcgetattr(STDIN_FILENO, &oldtermios);
  newtermios = oldtermios;
  newtermios.c_lflag &= ~ICANON; // Turn off canonical mode.
  // Wait for 1 character only.
  newtermios.c_cc[VMIN] = 1;
  tcsetattr(STDIN_FILENO, TCSANOW,  &newtermios);
  do {
    printf("Enter four numbers:\n");
    int ns = scanf(" %d %d %d %d", &i[0], &i[1], &i[2], &i[3]);
    if(ns == EOF) {
      perror("Scan failed. Exiting");
      break;
    }
    else if(ns != 4) {
      printf("\nScan failed. Only read %d numbers. Press enter to continue.\n", ns);
      while((i[0] = getchar()) != '\n' && i[0] != EOF);
    }
    else {
      printf("\nScanned %d numbers %d %d %d %d\n", ns, i[0], i[1], i[2], i[3]);
    }
  } while(1);
  return 1;
}
+4

getch(). Enter.

0

scanf C. , enter.

. curses. posix windows pdcurses (, , ).

Sample code and a really good tutorial can be found here: http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/init.html#ABOUTINIT

0
source

Source: https://habr.com/ru/post/1665088/


All Articles