Reputation: 41
Is there a function that makes a command prompt program wait like system("pause")
, and continues running only after accepting a certain key?
Upvotes: 0
Views: 1337
Reputation: 3166
If you're on Windows, you can use kbhit() which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit thus
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
Compiling steps :
gcc -o kbhit kbhit.c
When run with
./kbhit
It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).
(Got over internet - you can modify code and use specific ch value like \n for Enter key)
Upvotes: 0
Reputation: 223183
If you're waiting for a newline character, there's an easy and portable way to do that. Just use getline
.
If you want to receive other characters without receiving a newline first, then things are less portable. In Unix systems, you'll need to set your terminal to "raw mode". As George's comment mentions, ncurses is an easy way to do this, plus it provides handy functions for drawing things to a specific place in the terminal, receiving arbitrary keys, etc.
On Windows, you'll need to use its console interface. This is, of course, not usable outside of Windows.
As Neil Butterworth comments, there's also a version of curses that works for Windows, called PDCurses. If you need to write software that works for both Unix and Windows, that's a good option to pursue.
Upvotes: 2
Reputation: 904
If getline and ncurses don't work for you there is always conio.h and getch(). There are some problems with this as explained in this answer Why can't I find <conio.h> on Linux?
Good luck.
Upvotes: 0