Reputation: 22011
I am looking for a Console function that waits for the user to press a key. I want it to be like Pascal's readkey; as in a Console Only solution. No GUI library / Graphics Library / Windowing Library / WinApi Calls (Windows). It should be cross-platform and (preferably) part of the C std library or C++ Class Library. So is there any such function / class method etc. ?
Upvotes: 3
Views: 13715
Reputation: 1
Simple:
getchar();
Literally the equivalent for readkey()
in C#.
Upvotes: 0
Reputation: 8694
If you're in a Windws run-time environment, you can use the non-standard C function kbhit( ). And there's a C-language Linux equivalent for Windows kbhit( )
. The function does just what you want: it will tell you if a keyboard character has been typed without reading the character; or, alternatively, will read and deliver to you one character iff one has been typed. You can find it over here:
http://pwilson.net/sample.html
Scroll down to the paragraph headed "Single-character keyboard input for Linux and Unix"
HTH
Upvotes: 1
Reputation: 6305
As far as I know there is no portable solution for your item. In windows, you can use the header <conio.h>
which has a function called getch()
for getting a char directly from the console. If you are in Linux, then you can use the library ncurses.
Upvotes: 2
Reputation: 108967
The C Standard library has no notion of a "keyboard buffer". input/output is mostly line-based (triggered when ENTER is pressed).
You have a few options:
setvbuf()
and use fgetc()
(and wait for ENTER if you didn't change the buffering strategy)Upvotes: 6