Is there a function that makes a command prompt program wait like system("pause")
, and continues running only after accepting a certain key?

- 41
- 1
- 6
-
2you might want to take a look at [ncurses](https://www.gnu.org/software/ncurses/) – George Jan 25 '17 at 18:22
-
Do you mean like stepping through code one line at a time? – ArmenB Jan 25 '17 at 18:27
-
1Not in the C++ Standard Library. – Jan 25 '17 at 18:27
-
Also are you talking about a "normal" command line program or something platform specific or ...? And what is the program supposed to do while waiting? absolutely nothing (in which case you could just use blocking IO)? – UnholySheep Jan 25 '17 at 18:28
-
To clarify, I want it to work like system("pause"), except that it only accepts a certain key. I'll edit the question. – Twilight053 Jan 25 '17 at 19:14
-
Which os are you using..i guess system pause doesn't work on Linux does it? – minigeek Jan 25 '17 at 19:20
3 Answers
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.

- 219,335
- 46
- 382
- 435
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.
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)

- 2,766
- 1
- 25
- 35