Is there an equivelant for Pascal's readkey; in C or C++?

11,278

Solution 1

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:

  • use an external library like ncurses
  • change the terminal buffering strategy with setvbuf() and use fgetc() (and wait for ENTER if you didn't change the buffering strategy)

Solution 2

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.

Solution 3

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

Share:
11,278
ApprenticeHacker
Author by

ApprenticeHacker

I try to make the internet faster.

Updated on June 04, 2022

Comments

  • ApprenticeHacker
    ApprenticeHacker almost 2 years

    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. ?