Get user input inside of loop [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I've seen it once or twice in a few places, but I can't seem to find this pattern while searching. What I want is, while in a loop, pause for a couple of milliseconds for user input, then continue.
so it would look something like this:
int main()
{
while (1)
{
//do stuff
//get user input, continue if there is nothing
//do stuff based off of user input
}
}
I'm using xemacs and g++ on Fedora 18 and I'm looking for a single keyboard keypress.

You'll (almost certainly) want to use the curses library.
If you want to pause to wait for input, you call halfdelay to set the time to wait for input. If the user hasn't entered anything in that time, it'll return ERR (or some error code anyway--been a while so I can't remember for sure what). If memory serves, however, the shortest delay you can specify is 1/10th of a second; there's no way to tell it to just pause for (say) up to 2 ms. Edit: thinking about it, it seems like there is a timeout (or something like that) that lets you set a timeout in milliseconds.
More often, you just want to react to input if there is any, and just continue other processing if here is none. In this case, you'd call nodelay.
Either way, you also want to call cbreak to disable line buffering at the OS level, so any key the user presses will be available to the program immediately instead of waiting for them to press return before you receive the input.
I'd guess you probably also want to call noecho() so the user's input isn't echoed by getch. For the kind of program you seem to be talking about, echoing the input command is rarely desired.
Then inside your loop, you'll call getch() to get the key input data (if any). If you get input, you process it. If it returns the error code to indicate there's no input, you continue your other processing.
So the code would be structured something like:
cbreak();
noecho();
nodelay(mywindow, true);
while (1) {
int ch;
if (ERR != (ch = getch()))
process(ch);
update_screen();
do_other_processing();
}

In the case of wanting a keyboard input, and then firing a trigger only if it is there, your best bet is essentially to use an event handler style system, something akin to how games detect input. What happens is usually something like this:
Event e;
while(Poll for event e) // Basically check if something has been triggered.
{
if(event type == certain key pressed){
// Do related stuff
}
}
You will essentially put this inside your main program loop, and every time that key, or some other trigger you specify is fired, it will call a function or do something else you specified.

Related

How do I std::cout and std::cin at the same time? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to create a console application that works as a messaging app running off of a server. I want to be able to recieve messages from a friend while I am typing my own message or while the console is awaiting my input (essentially I want to be able to cout while I cin). how would I do this? I'm assuming I will have to work on multiple threads but I cant find anything useful online.
Yes, you will have to work with multiple threads. Essentially, one thread creates and sends messages, one thread receives them. So, they work in parallel and whenever a message is received it is simply printed (or written to a log or what have you) from the reader thread, and the writer thread will constantly be waiting for user input, and will allow the user to send a message. In this code, the message is printed as soon as its received. Also, this code is highly simplified since I have no idea how your message implementation is done, so all the message specifics are left out and a generic message is just printed at some interval. This kind of implementation will also result in messages received cutting off input. You would need some kind of input space separate from the output space so they don't intercept eachother visually like this, or you could use mutexes but this defeats the purpose of getting a message instantly.
#include<iostream>
#include<thread>
#include<chrono>
void reader()
{
using namespace std::chrono_literals;
for(int i = 0; i < 10; i++)
{
std::this_thread::sleep_for(1000ms);
std::cout << "This is a message...\n";
}
}
void writer()
{
std::string message;
for(int i = 0; i < 10; i++)
{
getline(std::cin, message);
}
}
int main(void)
{
std::thread reader_thread(reader);
std::thread writer_thread(writer);
reader_thread.join();
writer_thread.join();
std::cout << "done!\n";
}
EDIT: Thought I would give more pointers on cin/cout intercepting each other. Basically, input and output happens in the same line and same place in most console implementations (Unless you use redirection or pipes or something). Most actual messaging apps have separate places for input and output. For example, you input your message somewhere, but the messages you receive show up above that. This kind of implementation means that input/output never stack on top of each other, but is also pretty much impossible to do with cin/cout. So, if you really want to do this kind of messaging application, you could use pipes or files OR you could use some libraries. Pretty much any GUI lib (Gtkmm, Qt) will let you do something like this, but if you are console-bound, ncurses will let you manipulate the console in complex ways like this so you can have one section for receiving messages and one for sending them.

Is it possible to create "quick time events" in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have some knowledge about C++, but I stumbled upon an problem. I want the user to enter some text, but when it takes longer than X seconds, the program will go on. I guess, it is not possible, but maybe you know something about it.
It will be in the command line, without GUI.
I am not certain how the programm will look like, but it will be something like a CMD-RPG. I wanted to use Quick Time Events to make it a little bit more exciting.
I cant comment so I will just leave this here
Input with a timeout in C++
Since I cannot comment, I will simply leave this as an answer.
One possible way to solve this problem is to have 2 threads:
Input capture thread: since receiving input is a thread-blocking action, you should have a thread that simply polls for user input, placing that input into a thread-safe buffer
Quick-time function on main thread: a function that will be responsible for executing the quick-time event. Something like the following could be done (pseudo code):
clear input buffer //the buffer provided by the input capture thread
bool success = false;
while(current time < ending time)
{
if(input buffer isn't empty)
{
get contents of input buffer and send contents to cout
if (user has finished input correctly)
{
success = true;
break;
}
clear buffer
}
}
return success;
For this to work, you would need to turn off echo on the command prompt (see this page for more info)
Although Diogo's reference is excellent (and informative), I believe this answer is more applicable than since the OP has indicated that this program will be ran on Windows.

C++ Primer 1.4.4 — Importance of EOF and how to write in a code that will end without EOF?

Referring to two questions:
Incorrect output from C++ Primer 1.4.4
Confused by control flow execution in C++ Primer example
My question is answered in both of those posts, but I want to delve further.
First, I know this is only the beginning, but let's say I make a fully functional program that runs in a designed window. By that level, will I already know how to implement a EOF? I can't expect someone running my program to know that they need to hit Control-Z.
Is there a way to implement a specific code that functions so that it does not need me to type in an unrecognized value?
Also one guy in those questions somewhat answered the importance of EOF, but how come the program doesn't even post the final cnt - 1?
Let's say I do the numbers 10 10 10 20 20 20. Without EOF, this will only show the "10 repeats 3 times." How come the program doesn't at least type in the count "10 repeats 3 times and 20 repeats 2 times" minus the final one with white space?
lets say I make a fully functional program that runs in a designed window. By that level, will I already know how to implement a eof? I can't expect someone running my program to know that they need to hit ctrl + z.
You could either tell the user explicitly to do a specific action to end input or the design of the window itself could tell the user the information implicitly. For instance, a dialog box could ask the user to enter input and click an OK button when done.
Is there a way to implement a specific code that functions so that it does not need me to type in an unrecognized value?
It seems like you would rather use a newline character to terminate your input. An example of this usage could be std::getline. Instead of writing
while (std::cin >> val)
you could instead use
std::string line;
if (std::getline(std::cin,line))
and assume that your user's input only consists of one line of values. There are plenty of other ways to similarly achieve this task depending on how you want to constrain the user's input.
Let's say I do the numbers 10 10 10 20 20 20. WIthout eof this will only show the "10 repeats 3 times." How come the program doesn't at least type in the count "10 repeats 3 times and 20 repeats 2 times" minus the final one with white space?
Without the eof your program is still executing the while (std::cin >> val) loop since std::cin >> val has not yet received invalid input.
Since the line
std::cout << currVal << " occurs " << cnt << " times" << std::endl;
occurs after that while loop finishes execution, you don't (yet) see any information about the three 20's in the input.
When you are reading a sequence of inputs you'll need some indication when your down. That could be a sentinel value ("enter 999 to stop reading"; you'd need to detect that while reading), an invalid input ("enter X to stop reading"; when reading an int the value X is illegal and causes the stream to got into failure mode, i.e., have std::ios_base::failbit set), or the more conventional "there isn't anything more to read". For a file, the last conditions is straight forward. When reading data from the console you'll either need to teach people how to terminate the input or you'll need to use a different approach.
If you want to intercept any keypressed and react on them directly you may do so, too. You could, e.g., use ncurses and control your input via that. You could also set the concole to non-buffering (on POSIX systems using tcgetattr() and tcsetattr() to clear the ICANON flag) and deal directly with all key presses to decide whether you want to continue reading or not.
Although I'm certainly up to doing fancy I/O stuff I normally don't bother: users will understand the "end of input" character and just deal with it. That is, my input normally looks something like this:
while (in >> whatever_needs_to_be_read) { ... }
... or, if the input is genuinely line oriented
for (std::string line; std::getline(in, line); ) { ... }
The function doing this input will then be called with a suitable std::istream which may be std::cin although I have typically some way to also read from a file (in addition to the shell-privided input redirection).
BTW, despite some indications in the questions referenced, "EOF" is not a character being read. It is a character entered, though (normally). ... and it is quite conventional to "know" the end of input character (on POSIX systems a ctrl-D and on Windows a ctrl-Z). You can use other indicators, e.g., the "interrupt" (ctrl-C) but that takes more work and doesn't integrate nicely with stream. To use the interrupt chacter you'd need to setup a signal handler for SIGINT and deal with that. One slightly annoying part of doing so is that if you get it wrong you'll need to find a different way to kill the program (e.g. on POSIX using ctrl-Z to put the process to sleep and kill it via a harsher signal).

Scanf with Signals

I have a signal that blocks SIGINT and basically says "Sorry, you can't quit.\n"
The issue is this can occur during a scanf.
When this occurs during a scanf, scanf takes in the printf as input.
How can I do a printf that will cause scanf to basically hit the enter key automatically. I don't care that I am getting bad input. I just want to programatically finish that scanf with a printf or something else.
Process:
scanf("get stuff")
-> User is able to enter stuff in.
-> SIGINT occurs and goes to my handler.
-> Handler says "Blah blah blah" to stdout.
-> Scanf has taken this blah blah blah and is waiting for more input.
How do I make it so that when I return scanf is finished (don't care what it has gathered I just want it to continue without user help).
EDIT: if I send two signals then the scanf terminates. I want to emulate the ending of the scanf somehow programatically.
Your question suggests you are confused - or perhaps English is not your native language.
I have a signal that blocks SIGINT and basically says "Sorry, you can't quit.\n"
What you might have is a signal handler that is set to respond to SIGINT. Further, you might be using the 'signal()' function to set the handler - but you should be aiming to use the POSIX standard 'sigaction()' function to set the handler instead.
The issue is this can occur during a scanf.
In context, 'this' is presumably an interrupt signal, typed by the user who wishes to stop your program. Be cautious about stopping people exiting a program with an interrupt signal; if you don't let them do that, they will be more brutal. That might mean they'll generate SIGQUIT (and perhaps a core dump) instead; if you block that too, there are a number of other tricks they can try until they get to the ultimate 'kill -9 pid' which your program will get no chance to react to.
When this occurs during a scanf, scanf takes in the printf as input.
This is confused...you are presumably implying that the output from a 'printf()' statement (presumably the one that says "You can't quit") is then being seen as input to the 'scanf()'? Which seems pretty improbable... It would require a very, very weird setup on the I/O of the process, and I'm still not convinced it can happen.
How can I do a printf that will cause scanf to basically hit the enter key automatically. I don't care that I am getting bad input. I just want to programatically finish that scanf with a printf or something else.
There are several possibilities - it depends in part on the O/S you are using (even if it is POSIX.) I don't use 'scanf()'; I find it too difficult to control. If your system resumes the reads after the interrupt handler returns, then you will have a difficult time. Sometimes, though, 'scanf()' will stop short and return the number of items it has processed. If the 'scanf()' you have does not terminate, then you will need to think about interposing a 'sigsetjmp()' in a function that simply calls 'setjmp()' and then invokes your function that calls 'scanf()'. Then your signal handler can use 'siglongjmp()' to return to that intermediate function:
sigjmp_buf trap;
int intermediary(int argument)
{
if (sigsetjmp(trap) == 0)
{
function_calling_scanf(argument);
return 0; // Success
}
// Report failure
return -1;
}
Your description continues:
Process:
scanf("get stuff") -> User is able to enter stuff in.
-> SIGINT occurs and goes to my handler.
-> Handler says "Blah blah blah" to stdout.
-> Scanf has taken this blah blah blah and is waiting for more input.
How do you know that scanf has read the 'blah blah blah'? It seems very, very improbable to me.
How do I make it so that when I return scanf is finished (don't care what it has gathered I just want it to continue without user help).
Use sigsetjmp().
EDIT: if I send two signals then the scanf terminates. I want to emulate the ending of the scanf somehow programmatically.
This is what indicates that you are using 'signal()' to set your signal handler and not 'sigaction()'. With 'signal()', when the interrupt occurs, the signal handler is set back to the default. With 'sigaction()', you have to request that behaviour; by default, the received signal (SIGINT) is blocked for the duraction and the signal handler remains in effect. If a second interrupt occurs while the first is running, the second is held up until the first handler returns (at which point the handler will be re-entered).
Don't use scanf as its buffering or retry code may get in the way. If you use a read(2) call it should return -1 with an errno of EINTR. Scanf may see that error and retry the read. You can always sscanf the data from the raw read.
This is assuming that QNX is POSIX compliant for read and you don't have the source for scanf for inspection.

Using SetKeyboardState along with GetKeyboardState in C++

I don't know how to write a good question here, but, basically, does anyone know where I can possibly find some C++ source code using these to actually set keyboard state? For some reason using it the way MSDN does on Windows 7 doesn't do...anything at all.
Basic code:
PBYTE keyState;
GetKeyboardState(keyState);
...
// Later on when I need to set the keyboard state (key pressed etc) back to original:
SetKeyboardState(keyState);
and ... nothing happens :(
From:
http://www.gamedev.net/community/forums/topic.asp?topic_id=43463
First off, GetKeyboardState() would be the wrong function to use because as Windows has a chance to process keyboard messages (whether you want it too or not) it updates the results of the keyboard's state for the next call to GetKeyboardState().
Here's a little function that I use to get the status of the keyboard's keys. Be carefull though, depending on how fast your main loop is, it may cause problems if you aren't expecting it.
You need to keep track of whether or not a specific key was pressed the last time you called the ReadKeyboard() function. If your loop polls the keyboard 30 times a second, then pressing a key once probably causes the key to be flagged 3 or 4 calls in a row. Rather confusing sometimes. Just thought I'd mention it.
void ReadKeyboard( char* keys )
{
for (int x = 0; x < 256; x++)
keys[x] = (char) (GetAsyncKeyState(x) >> 8);
}