c++ - 在 C++ 中阅读几秒钟

标签 c++ linux getline

我想知道我如何才能像你只有 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/

相关文章:

c++使用getline和FILE而不是ifstream读取文件

c++ - 你能在 std::getline 中指定什么不是定界符吗?

c++ - 我怎样才能让位域以正确的顺序排列我的位?

c++ - WC_NO_BEST_FIT_CHARS 未定义?

c++ - 处理中断时如何返回主 GUI 线程?

linux - 在 Linux Mint 21.2 MATE 64 位上的 nvim 中渲染文本对象时出现问题

linux - 从 unix 中的 .gz 日志文件中提取值

c - 将 C + Makefile 导入 linux IDE?

c++ - 为什么会抛出 out_of_range 错误?

c++ - 读取文件缓冲区传递