InterviewSolution
| 1. |
Solve : c++ only waiting set amount of time for user input? |
|
Answer» Im writting a program and i want to only wait a set amount of time, like 60 seconds, for the user to input their name. if 60 seconds go by and the user has not entered anything the program will move on. dodgy workaroundit won't work. I'm not even SURE why you think it will. Think about it. the system call will simply take as long as ping does to return. cin's stream input won't even be called until after that OCCURS; and if you imply that a cin is before that small block, that won't work either, because the original problem is that cin never returns until it has input, so cin won't return until after the input has been given, at which point it the program delays for no reason and always displays "timeout". Secondly, Nobody should EVER EVER EVER EVER use the "system" call to implement something like this, or anything, for that matter, except for shelling out another application that is not known until run-time. It's non-portable, and disgusting. If you want to write a batch file, you write a batch file, you don't create a line of "system()" calls and call it C (and certainly not C++). Third: if you aren't going to test your suggestions... what's the point? I don't even need to run that code to say it doesn't work. For the original question, there are two methods that I can think of: create a thread that gets input from the console. You can use WaitForSingleObject() (on windows) to wait on that thread for it to close. Or, you can read data from the STANDARD input character by character in a non-blocking way, this can be put in it's own function: Code: [Select]#include <cstddef> #include <ctime> #include <iostream> #include <conio.h> bool get_input ( char *buffer, std::size_t size, int timeout ) { std::time_t start = std::time ( 0 ); std::size_t n = 0; for ( ; ; ) { if ( n == 0 && std::difftime ( std::time ( 0 ), start ) >= timeout ) return false; if ( kbhit() ) { if ( n == size - 1 ) break; char ch = (int)getche(); if ( ch == '\r' ) { buffer[n++] = '\n'; break; } else buffer[n++] = ch; } } buffer[n] = '\0'; return true; } int main() { char buffer[512] = {0}; if ( !get_input ( buffer, 512, 5 ) ) { std::cout<<"Input timed out\n"; buffer[0] = '\n'; } std::cout<<"input: \""<< buffer <<"\"\n"; } |
|