问题
In main
, I give the user the ability to enter a command to stop the application:
while( run_processes && cin >> command_line_input ){
I'd also like to stop the application elsewhere by setting run_processes = false;
.
However, when I set run_processes
to false
, the above loop doesn't stop without the user entering input.
How can I properly interrupt the loop without the user entering input?
回答1:
It is not possible to interrupt std::cin
in a portable way.
You could however resolve to non-portable solution, e.g. manually poll()
the standard input on a UNIX system and check run_processes
while polling.
回答2:
Does cin not necessarily depend upon user input for the while to proceed?
Yes, the user would have to enter input each loop.
bool stop = false;
std::string command;
int count = 0;
while(stop==false && std::cin>>command)
{
++count;
std::cout<<count<<std::endl;
}
The code above only counts +1 after I enter something. Unless you are changing the value of run_process based on the user input I don't see why it shouldn't work...?
来源:https://stackoverflow.com/questions/24976180/interrupt-cin-while-loop-without-the-user-entering-input