在C ++中几秒钟内阅读

问题描述 投票:4回答:2

我想知道我怎样才能在5秒钟之内读取标准输入,就像您只有5秒钟的书写时间。

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr);
  cout << "Hello " << mystr << ".\n";
  cout << "What is your favorite team? ";
  getline (cin, mystr);
  cout << "I like " << mystr << " too!\n";
  return 0;
}

就像用户一直有时间要写。 getline或read是否有任何选择可以迫使getline在5秒后停止?

谢谢

c++ linux getline
2个回答
0
投票

一种可能的解决方案是使用poll()(在xubuntu 18.04上使用g ++ 7.5.0进行测试):


0
投票

API std::string getline_timeout(int ms, std::string def_value) { struct pollfd fds; fds.fd = STDIN_FILENO; fds.events = POLLIN; int ret = poll(&fds, 1, ms); std::string val; if (ret > 0 && ((fds.revents & POLLIN) != 0)) { //cout << "has data" << endl; std::getline(std::cin, val); } else { //cout << "no data" << endl; val = def_value; } return val; } 无法执行您想要的操作。您可以尝试两种方式:-多线程可以工作-具有复用IO的单线程,例如select / poll / epoll / iocp

© www.soinside.com 2019 - 2024. All rights reserved.