gpt4 book ai didi

在可能为空或可能不为空时清除 C 中的标准输入

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:36 24 4
gpt4 key购买 nike

我是一名编程专业的学生,​​正在寻找一种方法来摆脱可能在标准输入中徘徊的字符。我已经尝试过这里以各种形式给出的技术,您可以在其中执行如下操作:

void clearStdIn(void) 
{
char c;
while((c = getchar()) != '\n' && c != EOF)
/* discard */ ;
}

问题似乎在于,如果开始时标准输入中没有任何内容,则该函数会等待用户按下回车键,然后控制流才能继续。我应该怎么办?

最佳答案

可以像这样在不阻塞的情况下刷新输入流(以可移植的方式):

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int flush_inputstream(int fd)
{
int result = 0;

int flags = fcntl(fd, F_GETFL);
if (-1 == flags)
{
perror("fcntl() failed getting flags");

result = -1;
goto lblExit;
}

if (!(flags & O_NONBLOCK)) /* If stream isn't non-blocking */
{ /* set it to be non-blocking. */
result = fcntl(fd, F_SETFL, O_NONBLOCK);
if (-1 == result)
{
perror("fcntl() failed setting O_NONBLOCK");

goto lblExit;
}
}

/* Loop reading from the stream until it is emtpy: */
do
{
char c = 0;
ssize_t bytesRead = read(fd, &c, 1);
if (-1 == bytesRead)
{
if ((EAGAIN != errno) && (EWOULDBLOCK != errno))
{
perror("read() failed");

result = -1;
}

break;
}
} while (1);

if (!(flags & O_NONBLOCK)) /* If stream had not be non-blocking */
{ /* re-set it to not be non-blocking. */
int result_fcntl = fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
if (-1 == result_fcntl)
{
perror("fcntl() failed setting flags");

if (0 == result) /* Do not overwrite prvious error! */
{
result = result_fcntl;
}

goto lblExit;
}
}

lblExit:

return result;
}

/* To test this: */
int main(void)
{
int fd = fileno(stdin);

printf("Feed some chars via the keyboard now!\n");

sleep(3);

printf("Game Over! Press enter to see stdin is empty\n");

if (-1 == flush_inputstream(fd))
{
fprintf(stderr, "flush_inputstream() failed");
return EXIT_FAILURE;
}

char s[16] = "";
if (NULL == fgets(s, sizeof(s), stdin))
{
perror("fgets() failed");
}

printf("%s\n", s);

return EXIT_SUCCESS;
}

关于在可能为空或可能不为空时清除 C 中的标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com