我写了一个小程序,
int main(int argc, char *argv[])
{
int n;
std::cout << "Before reading from cin" << std::endl;
// Below reading from cin should be executed within stipulated time
bool b=std::cin >> n;
if (b)
std::cout << "input is integer for n and it's correct" << std::endl;
else
std::cout << "Either n is not integer or no input for n" << std::endl;
return 0;
}
读自std::cin
正在阻塞,因此程序会等待,直到有外部中断(也如信号)向程序或用户提供一些输入。
我该如何发表声明std::cin >> n
等待一段时间(也许使用sleep()
系统调用)用于用户输入?
如果用户未提供输入,并且在规定时间(假设 10 秒)完成后,程序应恢复执行下一条指令(即if (b==1)
声明开始)。
这对我有用(请注意,这在 Windows 下不起作用):
#include <iostream>
#include <sys/select.h>
using namespace std;
int main(int argc, char *argv[])
{
int n;
cout<<"Before performing cin operation"<<endl;
//Below cin operation should be executed within stipulated period of time
fd_set readSet;
FD_ZERO(&readSet);
FD_SET(STDIN_FILENO, &readSet);
struct timeval tv = {10, 0}; // 10 seconds, 0 microseconds;
if (select(STDIN_FILENO+1, &readSet, NULL, NULL, &tv) < 0) perror("select");
bool b = (FD_ISSET(STDIN_FILENO, &readSet)) ? (cin>>n) : false;
if(b==1)
cout<<"input is integer for n and it's correct"<<endl;
else
cout<<"Either n is not integer or no input for n"<<endl;
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)