C++ Clear an Input Buffer - c++

As of now, I'm making a program with different screens that use the escape key to exit, but what happens is if I press escape in, lets say the option menu. And then I go into the game, which the game allows escape to exit out, it will automatically leave the game. If that makes sense. :), but, it seems like the escape key floats around in the input buffer, and I tried many ways to clear it but I can't find a way. Here is a part of my code.
int Controls()
{
// Allows us to get a key when pressed
int Key;
Key = _getch();
switch(Key)
{
// Number 27
case KEY_ESCAPE:
do code...
break;
}
return Key;
}

Try doing a
fflush(stdin);
whenever you transition to any new page. It clears the input stream.

Related

How to implement an "ENTER" case into a switch statement

I am working on a class project where I have to create an ordering system for a coffee shop in C++. If it is applicable, I'm working in Visual Studio.
In the project outline, the teacher said that there is a simple integer input to navigate the menu; however, he specifies that if NOTHING is inputted (I'm assuming what I've seen called a "hot enter") that it calculates the receipt and the program resets.
I have tried cin.get() and checking if the buffer is '\n', and this works fine, but my current implementation seems to only be able to capture a hot enter, and fails to roll into the switch case.
For getting input from the user, I've currently tried this:
// Get menu input
if (cin.get() == '\n') { // Check if user hot entered, assign value if so
input = 0;
} else { // If not, do it normally
input = cin.get();
}
However this does not work quite right, and fails to capture inputted integers for use in the switch case. I'm unsure if this sort of implementation is sound in reasoning, or whether there is a much simpler route to have a case for a hot enter.
I don't receive any errors, so I imagine there is something wrong with my understanding of how these functions work, or my implementation is flawed in its logic.
Thank you.
You used cin.get() twice. The second cin.get() in input = cin.get(); is redundant.
// Get menu input
input = cin.get();
if (input == '\n') { // Check if user hot entered, assign value if so
input = 0;
}
//else { // If not, do it normally
// input = cin.get();
// }

How can I block certain keys in C++ with NCurses

I'm new to C/C++ and I'm making a simple text user interface with NCurses.
Whenever I scroll up/down with the mouse wheel, or press arrow keys, the console echos characters like:
"[[A^[[C^[[B^[[D"
to show me that I've pressed the keys.
I would like to stop these from echoing and only echo basic keys (punctuation and letters).
Here is my main loop. I basically want it to be my own console with commands that I create.
string input;
char inputArr[80];
while (input != "q" && input != "quit" && input != "exit" && input != "leave") {
printw(" > ");
refresh();
getstr(inputArr);
input = inputArr;
if (input.substr(0, 3) != "someCommand") {
printw("\n ~ %s\n\n", inputArr);
refresh();
} else
execCmd();
}
quit();
For the most part I believe it is C++ but I do have a C function (that uses libCurl).
Also, is there no cleaner way to read in strings with NCurses? I dont really like using char arrays (I'm used to Java).
Call noecho() somewhere close to initscr().
This will avoid clobbering your screen with unwanted input. If you want your users to see what they type later on, you will need to call echo() before, however.

Multithreaded console I/O

I'm using a console in my multithreaded application. Right now, it only accepts output (printf and the like) and so far I have no issues. However, I want to be able to support console input as well, and this is where my life gets complicated.
To forewarn, I'm very unfamiliar with the more complicated nuances of working with console input and output. My experience in the subject doesn't go much further than printf/cout, scanf/cin, and using SetConsoleTextAttribute() to change the color (on windows).
I would prefer to keep my program as cross-compatible as possible, but I'm not opposed to having to write platform-specific code, as long as I can find viable alternatives for other platforms.
Conceptually, I'd like the console to run on it's own thread, so that it can lock up while waiting with cin without freezing the whole program or one of the other threads. Any thread could send console output to this thread which would output it in a clean manner (probably using a thread-safe queue), and any input that the console reads would send the command off to the appropriate thread.
My first problem is that while I'm typing some input, any output will show up in the middle of what I'm typing. The solution I would like to handle this would be to reserve the bottom line of the console for input, and have output go to the second last line, pushing the input line down. How can I do this?
You really don't want to go down the road of trying to reserve part of the console for input while writing to the rest of the console. At least, not if you're just writing scrolling text. It's possible, but fraught with error and way more trouble than it's worth. See Async Console Output for a few hints of the problems.
Certainly, it's not possible to do this using just conio.h.
You could allocate two console screen buffers, with one being for input and one for program output. When your program is running normally, the output screen buffer is selected and you see the output scrolling on the screen. But when your program is waiting for user input, you swap screen buffers so that the output is still going, but in the other screen buffer.
You end up having to format the output yourself and call WriteConsoleOutput, passing it the handle of the screen buffer you want to write to. It gets complicated in a real hurry, and it's very difficult to get right. If it's even possible. I know I've spent way too much time on it in the past, and there were always odd problems.
I won't say that what you want to do isn't possible. I will say, however, that you're going to have a tough time with it.
Wellp, I solved it using pdcurses. In case someone else wants to do something similar, here's how I did it. First, I initialize the console thusly:
Console::Console(bool makeConsole)
{
if (makeConsole == false)
return;
if (self)
throw ("You only need one console - do not make another!\n");
self = this;
#ifdef WIN32
AllocConsole();
#endif
initscr();
inputLine = newwin(1, COLS, LINES - 1, 0);
outputLines = newwin(LINES - 1, COLS, 0, 0);
if (has_colors())
{
start_color();
for (int i = 1; i <= COLOR_WHITE; ++i)
{
init_pair(i, i, COLOR_BLACK);
}
}
else
wprintw(outputLines, "Terminal cannot print colors.\n");
scrollok(outputLines, TRUE);
scrollok(inputLine, TRUE);
leaveok(inputLine, TRUE);
nodelay(inputLine, TRUE);
cbreak();
noecho();
keypad(inputLine, TRUE);
initCommands();
hello("Starting %s.\n", APP_NAME);
hellomore("Version %i.%i.%i.\n\n", APP_MAJORVER, APP_MINORVER, APP_REVISION);
}
Next, This is the function responsible for handling output. It's actually very simple, I don't need to do anything special to keep it thread-safe. I might simply not have encountered any issues with it, but an easy fix would be to slap a mutex on it.
void Console::sendFormattedMsg(short prefixColor, const char* prefix, short color, const char* format, ...)
{
if (!self)
return;
va_list args;
va_start(args, format);
if (has_colors())
{
if (prefix)
{
wattron(outputLines, A_BOLD | COLOR_PAIR(prefixColor));
wprintw(outputLines, prefix);
}
if (color == COLOR_WHITE)
wattroff(outputLines, A_BOLD);
wattron(outputLines, COLOR_PAIR(color));
vwprintw(outputLines, format, args);
wattroff(outputLines, A_BOLD | COLOR_PAIR(color));
}
else
{
wprintw(outputLines, prefix);
vwprintw(outputLines, format, args);
}
wrefresh(outputLines);
va_end(args);
}
And finally, input. This one required quite a bit of fine-tuning.
void Console::inputLoop(void)
{
static string input;
wattron(inputLine, A_BOLD | COLOR_PAIR(COLOR_WHITE));
wprintw(inputLine, "\n> ");
wattroff(inputLine, A_BOLD | COLOR_PAIR(COLOR_WHITE));
wprintw(inputLine, input.c_str());
wrefresh(inputLine);
char c = wgetch(inputLine);
if (c == ERR)
return;
switch (c)
{
case '\n':
if (input.size() > 0)
{
sendFormattedMsg(COLOR_WHITE, "> ", COLOR_WHITE, input.c_str());
cprint("\n");
executeCommand(&input[0]);
input.clear();
}
break;
case 8:
case 127:
if (input.size() > 0) input.pop_back();
break;
default:
input += c;
break;
}
}
This is run every frame from the same thread that handles window messages. I disabled wgetch()'s blocking behavior using nodelay(), eliminating the need to have console input running in it's own thread. I also disable echoing and echo the input manually. Enabling scrolling on the input window allows me to clear it's contents using a simple "\n", replacing it with updated contents if the user has typed anything. It supports everything one would expect from a simple, multi-threaded terminal capable to typing input as well as receiving output from multiple threads.
To disable echoing characters check this out:
Reading a password from std::cin
Maybe combine that with this guy's blog post on non-blocking Win32 console io.
You might also find this stuff useful:
conio.h,
pdcurses

Reading ESC on Linux during unbuffered input in C

I wrote a getch function for program. I couldn't use curses as it breaks the terminal for iostream I already use. The code:
inline std::string getch() {
char inp[4];
system("stty raw");
inp[0] = std::cin.get();
if(inp[0] == 27 && (inp[1] = std::cin.get()) != std::char_traits<char>::eof()) {
std::cin>>inp[2];
inp[3] = '\0';
}
else {
inp[1] = '\0';
}
system("stty cooked echo");
return std::string(inp);
}
I know it would be better to use termios.h instead of system calls. Everything works fine except if ESC key. I'm trying to capture arrows which are string of for example "\1B[A". When I detect ESC as first character I also read the second two to get full key code.
The problem is that it shouldn't occur when I press ESC as it's code is 1B alone. The cin.get() should return EOF when the buffer is empty during read, but it simply stops.
Is there a way to read ESC key on linux without using curses? Why my solution isn't working?
Thanks
After many hours of searching I found the solution. I had to use read function from unistd.h
It fills an array of given size, with characters from the input. When a key is pressed the buffer is filled with all read characters (works also on multiple keys). So an ESC has simply {27,0,0,...,0} and arrow {27,'[','A',0,0,...,0}.
I've rewritten my function using termios.h and put in library, so anyone can benefit.
Here is the code:
readkey on github

C++ - Making an event loop

Does anyone know how to make an event loop in c++ without a library? It doesn't have to be cross-platform, I'm on a Mac. Basically, I want the program to run and do nothing until the user presses the up arrow key, then the program will output "You pressed up" or something. All i can think of is having an infinite while or for loop and get input with cin, but I don't think cin can detect arrow keys and I believe it pauses the program until it reaches a '\n';
I would want it to look like this:
void RUN()
{
while(true)
{
// poll events and do something if needed
}
}
int main()
{
RUN();
}
I'm kinda sure it's possible without threads, and I've heard that this can be accomplished with fd_set or something, but I'm not sure how.
Any help would be really appreciated.
EDIT:
The program has to run in the background when there aren't any events. For example, Microsoft Word doesn't stop until the user presses a button, it keeps running. I want something like that, but command-line not GUI.
Since you're talking keyboard input, and not looking for a Mac look and feel, what you want is the UNIX way of doing it. And that is,
1) set the terminal in either raw or cbrk mode (I forget which).
2) now use read() to read single characters at a time.
3) temporarily echo the character read (as an int) so you can find what the up arrow key gives you.
As for the more general event loop question, where the only input device is the keyboard, you sit in a loop, and whenever a key is typed (in raw mode?) you call a routine with the value of the key typed. If you had more input devices, you would need multiple threads each could listen to a different device, putting what they find on a queues (with appropriate locking). The main loop would then check the queue and call a routine appropriately everytime something appears in it.
You can use ncurses and enable cbreak to get the raw input stream.
I've used a while loop with signal handlers. Like this incomplete snippet.
void getSomething()
{
std::cout << "Enter new step size: "; std::cout.flush();
std::cin >> globalVariable;
std::getchar(); // consume enter key.
}
void printCommands()
{
std::cout << "1: do something\n"
<< "q: quit\n"
<< "h: help\n"
<< std::endl;
}
void getCommand()
{
// Output prompt
std::cout << "Enter command ('h' for help): "; std::cout.flush();
// Set terminal to raw mode
int ret = system("stty raw");
// Wait for single character
char input = std::getchar();
// Reset terminal to normal "cooked" mode
ret = system("stty cooked");
std::cout << std::endl;
if (input == 'h') printCommands();
else if (input == '1') getSomething();
else if (input == 'q') {
g_next = true;
g_quit = true;
}
}
void
signalHandler(int signo)
{
if (signo == SIGINT) {
g_next = true;
} else if (signo == SIGQUIT) {
getCommand();
}
}
int main(int argc, char* argv[])
{
signal(SIGINT, signalHandler);
signal(SIGUSR1, signalHandler);
signal(SIGQUIT, signalHandler);
do {
// Stuff
} while (!g_quit);
exit(0);
}
The question has been updated to say "The program has to run in the background ... but command-line not GUI."
All traditional; *NIX shells that can put a program into the background also disconnect the program's standard input from the terminal, so AFAIK, this has become impossible.
This does not need to be Mac specific. The Mac supports *NIX mechanisms for reading characters from a keyboard.
AFAICT all the program is doing is waiting for a character, so it might as well block.
Normally the terminal device, tty (teletype!), is interpreting characters typed on the keyboard before your program can read them from standard input. Specifically the tty device normally buffers an entire line of text, and intercepts the rubout character (and a few others like CTRL+w) to edit the line of text. This pre-processing of characters is called a 'line discipline'
You need to set the tty device driver to stop doing that! Then you can get all of the characters the user types.
You change the device using ioctl or termios on the file descriptor.
Search for e.g. "ioctl tty line discipline raw" to understand the details, and find program examples.
You can set the terminal to 'raw' using the command line program stty.
Please read the stty man page because setting it back can be slightly tricky (NB: if you make a mistake it is often easier to kill the terminal, than try to fix it, because there is not echoing of anything you type)
It is possible that the up-arrow is not a single char, so it will require some byte-at-a-time decoding to avoid blocking at the wrong point in the input stream, i.e. if some input sequences are one character, and others two, or three characters, the decoding needs to happen at each byte to decide if there is a pending byte, or one too many read's might get issued, which would cause the program to block.