I am making a code in c++ in which I need a way to add timeout to user input like we have in python, i.e. in pyinputplus library we have timeout like inputNum(timeout=10). Is there any way to do this thing in c++.
Asked
Active
Viewed 103 times
0
-
1Using plain standard C++? Not really. You could create an independent thread whose result is ignored if its beyond the timeout. – Some programmer dude May 09 '21 at 02:22
-
Not in standard C++, no. You'll need to read the documentation for your compiler/library to find a solution - most often, there is a solution, but it will be specific to your compiler, library, and host system – Peter May 09 '21 at 02:22
-
1With that said, if you're willing to use system-dependent functions there are usually such capabilities. But then you have to tell us what operating system you're targeting. – Some programmer dude May 09 '21 at 02:25
-
I think the best solution is to generate a child thread that fetches the user input. The main thread would then wait for a set time and fetch the thread's output. The `std::thread` is what you are looking for. [Thread documentation](https://www.cplusplus.com/reference/thread/thread/), [Thread return value example](https://stackoverflow.com/questions/7686939/c-simple-return-value-from-stdthread) – Nicholas Obert May 09 '21 at 07:10
-
Does this answer your question? [Is it possible to set timeout for std::cin?](https://stackoverflow.com/questions/9053175/is-it-possible-to-set-timeout-for-stdcin) – Rushikesh Talokar May 09 '21 at 08:10
-
I was trying to know if there is some library function in c++ to do so, but from the answer I guess there isn't. So thanks for clarifying. – Hemendra May 09 '21 at 11:27