Nidhin David
Nidhin David

Reputation: 2474

How do I read character in C++ without pressing ENTER and without getch() or getche()?

In C, I could use getch() for getting an input without having the user to press enter. Is there a standard function in C++ that performs the functions of getch(). I don't want to use conio.h or other platform specific libraries.

while (choice!='q')
{
    cout << "Enter a six digit number(0 to 999999)";
    cin >> input;
    start.controller(input);
    cout << "Press r to repeat\nPress q to quit";
    cin >> choice;
}

I just want to repeat the process until user press q. Now user has to press ENTER key.

Upvotes: 1

Views: 4247

Answers (2)

user3920237
user3920237

Reputation:

This is somewhat covered by the C++ FAQ by Marshall Cline:

[15.17] How can I tell {if a key, which key} was pressed before the user presses the ENTER key?

This is not a standard C++ feature — C++ doesn't even require your system to have a keyboard!. That means every operating system and vendor does it somewhat differently.

Please read the documentation that came with your compiler for details on your particular installation.

(By the way, the process on UNIX typically has two steps: first set the terminal to single-character mode, then use either select() or poll() to test if a key was pressed. You might be able to adapt this code.)

The C++ standard also says § 1.9 [intro.execution]:

1 The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the observable behavior of the abstract machine as explained below.5

8 The least requirements on a conforming implementation are:

      — [..]

      — The input and output dynamics of interactive devices shall take place in such a fashion that prompting output is actually delivered before a program waits for input. What constitutes an interactive device is implementation-defined.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182761

No. The standard C++ library doesn't include any kind of terminal management. It doesn't even assume your terminal has any input capability other than lines. You need a library or code that understands how your particular terminal works.

Upvotes: 3

Related Questions