c++ - 检查标准输入是否为空

标签 c++ c stdin

我搜索了但没有得到这个问题的相关答案,我在 linux 机器上工作,我想检查标准输入流是否包含任何字符,而不从流中删除字符。

最佳答案

您可能想尝试 select()函数,并等待数据进入输入流。

描述:

select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking.

在您的情况下,文件描述符将是 stdin

void yourFunction(){
    fd_set fds;
    struct timeval timeout;
    int selectRetVal;

    /* Set time limit you want to WAIT for the fdescriptor to have data, 
       or not( you can set it to ZERO if you want) */
    timeout.tv_sec = 0;
    timeout.tv_usec = 1;

    /* Create a descriptor set containing our remote socket
       (the one that connects with the remote troll at the client side).  */
    FD_ZERO(&fds);
    FD_SET(stdin, &fds);

    selectRetVal = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);

    if (selectRetVal == -1) {
        /* error occurred in select(),  */
        printf("select failed()\n");
    } else if (selectRetVal == 0) {
        printf("Timeout occurred!!! No data to fetch().\n");
        //do some other stuff
    } else {
        /* The descriptor has data, fetch it. */
        if (FD_ISSET(stdin, &fds)) {
            //do whatever you want with the data
        }
    }
}

希望对您有所帮助。

关于c++ - 检查标准输入是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16228990/

相关文章:

c++ - std::numeric_limits<double>::epsilon() 可以用来做什么?

c# - 使用 C# 访问 C++ DLL 时出现间歇性访问冲突

c - 为什么严格的别名规则不适用于 int* 和 unsigned*?

c - gcc 调试符号(-g 标志)与链接器的 -rdynamic 选项

python - 多个测试用例标准输入 (Python)

python - 关于管道 stdio 和 subprocess.Popen

c - 使用 scanf 从标准输入 C 读取文件

c++ - std::any 用于不能复制构造的对象

c++ - 转换旧的 C 代码以使用线程

c - 如何在Matlab中使用Coder支持的tcp/ip?