I know that to make a simple yes or no question I can do this:

int Answer;
cin >> Answer;
if (Answer == 1)
{
Response
}
else
{
Response
}

But in the accounting program (In a recent thread), it registered the key before you hit enter.

What code do you have to add/change to make this program to respond instantly after you give a certain input? (pushing 1 and getting the response without having to hit "enter"

Dani AI

Generated

Good point by — standard C++ console input is line‑buffered, so a single keystroke normally won’t be delivered to the program until Enter is pressed. found a solution that works for their setup; for others the approach depends on the OS/terminal. Below are practical alternatives and pitfalls to watch for.

On Unix‑like systems the usual method is to put the terminal into noncanonical (raw) mode and read a single byte. That requires saving the terminal state, disabling canonical mode and local echo, doing a single read, then restoring the state (use RAII or an atexit handler so the terminal is always restored). Example pattern:

#include <termios.h>
#include <unistd.h>

termios oldt, newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
char c;
read(STDIN_FILENO, &c, 1);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

For Windows, use the console APIs or a portable library. If the program needs to work across platforms or handle special keys (arrows, function keys), prefer a library such as ncurses (Unix) or a cross‑platform alternative rather than hand‑parsing escape sequences. See the POSIX termios documentation and ncurses home page for details: termios manual, ncurses.

Troubleshooting tips: test in a real terminal (IDE console wrappers can behave differently), always restore terminal settings on exit (or use RAII), and remember special keys often send multi‑byte sequences that need parsing. If code works on one machine but not another, check the target platform’s console behavior and the runtime/library your compiler provides.

Recommended Answers

All 6 Replies

Member Avatar for Member #46692

Maybe use getch() or something equivalent, however, that has portability issues.

Thats what I thought but I can't seem to get any good information on it.

I tried using the source from the program I first saw this command in and it is set up like this:

char ans;
ans=_getch()

but that does not work in my code

Member Avatar for Member #46692

Have you got Dev-cpp?

Yes, that is what I am using.

Member Avatar for Member #46692

Then you need the header file #include <conio.h> and it is getch()

Then you need the header file #include <conio.h> and it is getch()

Yep that worked. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.