Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for user input in C?

Tags:

c

linux

I'm trying to make a simple command that pauses for user input. I think it'll be useful in Bash scripts.

Here's my code:

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

It doesn't even pause for user input.

I tried earlier to use getch() (ncurses). What happened is, the screen went blank and when I pressed a key, it went back to what was originally on the screen, and I saw:

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

It's somewhat what I wanted. But all I want is the equivalent of the pause command in DOS/Windows (I use Linux).

like image 915
biggles5107 Avatar asked May 13 '12 21:05

biggles5107


People also ask

How do you take input until Enter is pressed in C?

We should use "%[^\n]", which tells scanf() to take input string till user presses enter or return key. Scanf scans till user presses enter or till user presses return key.

What is the Getchar in C?

getchar is a function in C programming language that reads a single character from the standard input stream stdin, regardless of what it is, and returns it to the program. It is specified in ANSI-C and is the most basic input function in C. It is included in the stdio. h header file.

How does Getline work in C?

The getline method reads a full line from a stream, such as a newline character. To finish the input, use the getline function to generate a stop character. The command will be completed, and this character will be removed from the input.


1 Answers

From the GNU C Library Manual:

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

The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string. You must supply count characters worth of space in s, but the number of characters read is at most count − 1. The extra character space is used to hold the null character at the end of the string.

So, fgets(key,1,stdin); reads 0 characters and returns. (read: immediately)

Use getchar or getline instead.

Edit: fgets also doesn't return once count characters are available on the stream, it keeps waiting for a newline and then reads count characters, so "any key" might not be the correct wording in this case then.

You can use this example to avoid line-buffering:

#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");
}
like image 142
ccKep Avatar answered Sep 24 '22 14:09

ccKep