我想知道我如何才能像你只有 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 秒后停止?
谢谢
最佳答案
一个可能的解决方案是使用 poll()
并自己写 getline()
功能(在 xubuntu 18.04 和 g++ 7.5.0 上测试):
这里执行我的getline_timeout(int, std::string)
:
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 << "timeout / no data" << endl;
val = def_value;
}
return val;
}
#include <iostream>
#include <string>
#include <poll.h>
#include <unistd.h>
std::string getline_timeout(int ms, std::string def_value);
int main(int argc, char *argv[])
{
std::cout << "What's your name ? " << std::flush;
// Ask for the name
std::string mystr = getline_timeout(5000, "John Doe");
std::cout << "Hello " << mystr << std::endl;
std::cout << "What is your favorite team ? " << std::flush;
// Ask for the team
mystr = getline_timeout(5000, "Gryffindor");
std::cout << "I like " << mystr << " too!" << std::endl;
return 0;
}
关于c++ - 在 C++ 中阅读几秒钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61669196/