我搜索了但没有得到这个问题的相关答案,我在 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/