Interrupt cin while loop without the user entering input

女生的网名这么多〃 提交于 2019-12-12 12:23:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!