Wait for user input in C?

I am trying to make a simple command that pauses user input. I think this will be useful in Bash scripts.

Here is my code:

#include <stdio.h>
int main() {
  char key[1];
  puts("Press any key to continue...");
  fgets(key,1,stdin);
}

It does not even pause for user input.

I used to try using getch () (ncurses). It so happened that the screen went blank, and when I pressed the key, it returned to what was originally on the screen, and I saw:

$ ./pause
Press any key to continue...
$

This is what I wanted. But all I want is equivalent to a command pauseon DOS / Windows (I use Linux).

+3
source share
2 answers

From the GNU C library reference:

Function: char * fgets (char * s, int count, stream FILE *)

s, , . , s, , - 1. .

, fgets(key,1,stdin); 0 . (: )

getchar getline .

: fgets . count , , count, " " ​​ .

, :

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

int mygetch ( void ) 
{
  int ch;
  struct termios oldt, newt;

  tcgetattr ( STDIN_FILENO, &oldt );
  newt = oldt;
  newt.c_lflag &= ~( ICANON | ECHO );
  tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
  ch = getchar();
  tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );

  return ch;
}

int main()
{
    printf("Press any key to continue.\n");
    mygetch();
    printf("Bye.\n");
}
+10

, , , ,

linux Stdin , , 'enter' . , , ( ).

, , "getc", , termios , .

+2

All Articles