2012-03-13 58 views
0

我有一个计时器线程,将来会执行五秒钟,并有一个循环等待它完成执行。然后程序在用户输入时结束。我注意到,在等待循环的同时,输入被接受到输入缓冲区中,并用于完成该程序,并且任何后续的输入命中都被输入到命令行清除输入缓冲区,包括换行

我想忽略在“按Enter键退出”之前输入的所有输入,包括回车。我从事C++工作已经有一段时间了,我不记得如何做到这一点(我已经搜索过SO和Google,并且找不到这个特定问题的答案)。下面是我的例子:

std::cout << "Timer test: wait 5 seconds\n"; 
boost::asio::io_service test_io; 
deadline_timer test_timer(test_io, posix_time::seconds(5)); 

int testInt = 0; 
auto asynctest = [&testInt](const boost::system::error_code&) { 
    std::cout << "Running asynctest()\n"; 
    testInt = 5; 
}; 

std::cout << "Starting asynchtest, which should output in 5 seconds\n"; 
test_timer.async_wait(boost::bind<void>(asynctest, boost::asio::placeholders::error)); 

while(testInt != 5) { 
    std::cout << ". "; 
    boost::this_thread::sleep(boost::posix_time::milliseconds(200)); 
} 

// How do I clear all input from the input stream here so that if the user hit enter 
// during the timer countdown it will be cleared and user still must hit enter to 
// exit program? 

std::cout << "Press enter to exit\n"; 
std::cin.ignore(80, '\n'); 
return 1; 

ADSF

回答

2

有没有办法在纯粹的C++水平做到这一点;您必须将 降到操作系统级别,或者使用一些第三方库(如诅咒)(或者如果可以让它们异步读取cin ,则可能是某个异步IO库)。

+0

这不能用Boost的一些设施来完成吗?此外,顺便说一句,我在Visual C++中工作,显然MS提供了这样做的工具(未经测试 - 请参阅http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2007-01/ msg00389.html),但是这种做法违背了目的,因为这不是生产代码,而是自我检查,看看我有多生锈。 – taz 2012-03-13 14:29:12

+0

@taz我不知道'boost :: asio'如何与一个开放的'istream'交互;原则上,至少,如果可以将异步输入连接到您感兴趣的流,则可以使用非阻塞式读取来读取并抛出其中包含的所有内容。但是,我可能不会尝试使用'cin'工作,异步读取和'cin's缓冲区之间的交互可能是未指定的。 – 2012-03-13 14:35:19

+0

显然,我生锈了,足以立即尝试标准不支持的东西。从初步研究看来,你是对的,这可能与'boost :: asio'一起工作,可能需要线程。 C++ iostreams _do不do_非阻塞IO。 我不会进一步测试,因为我只是在练习。希望这会为未来挽救一些人头痛的问题。感谢您的帮助。 延伸阅读: http://www.gamedev.net/topic/538714-asynchronous-console-input/ http://bytes.com/topic/c/answers/841283-how-make-non-blocking -call-CIN – taz 2012-03-13 14:43:55