A
A
Alexey2014-06-24 15:44:08
HTML
Alexey, 2014-06-24 15:44:08

How to interrupt wait on input in C++?

Good day!
There is an infinite loop that accepts user commands. In the loop, respectively, there is a line: In a certain situation, I need to exit the loop by terminating the program, is it possible to interrupt the input waiting (without resorting to using std::exit)?
std::cin.getline(buffer, strlen(buffer));

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Misha Krinkin, 2014-06-24
@Renzo

just call break

In a certain situation
will not work?
UPDATE: if you do not want to block on input, then as far as I remember, C ++ can only help you here with the readsome method. Other options I know are system dependent, like posix aio.

R
RPG, 2014-06-24
@RPG

Not the best practice, but you can just close the stream that is asking stdin. Example with POSIX threads:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

void *worker(void *data)
{
    char buf[128];
    while(fgets(buf, sizeof(buf), stdin))
    {
  puts(buf);
    }
}

int main(int argc, char **argv)
{
    pthread_t t;
    pthread_create(&t, NULL, worker, NULL);
    sleep(3);
    pthread_cancel(t);
    pthread_join(t, NULL);
    return 0;
}

Sketched in C, but the essence should be clear.

A
AxisPod, 2014-06-25
@AxisPod

This function will not help you in principle, you need to use in this case you need functions that return the result immediately without waiting for actions from the outside, for example peek and organize your own input loop. Well, or read.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question