Answer the question
In order to leave comments, you need to log in
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
just call break
In a certain situationwill not work?
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question