c - 加载标准输入缓冲区

标签 c buffer stdin

我有一个调用 fgets() 的函数,使用 stdin 作为流,寻找用户输入。但是,在某些情况下,我宁愿让程序决定输入的内容,而不是要求用户输入。如果我能找到一种方法在使用 fgets() 调用函数之前用值加载 stdin 缓冲区,是否允许我不改变包含 的函数>fgets() 仍然接受程序输入?如果是这样,如何加载 stdin 缓冲区?

最佳答案

我有一个很酷的技巧,你可能会喜欢尝试:

#include <stdio.h>
#include <string.h>

int main(void) {
  char myString[100];
  char *hello = "hello world\n";
  int ii;
  for(ii=strlen(hello); ii>=0; ii--) ungetc(hello[ii], stdin);
  fgets(myString, 99, stdin);
  printf("I just read '%s'\n", myString);
  return 0;
}

当我编译并运行时,我得到:

I just read 'hello world
'

请注意,换行符 保留在字符串中(fgets 必须立即返回)- 因此您需要单独处理它。我不需要单独按回车键 - 只需运行程序即可。

我相信您可以根据自己的需要进行调整。

关于c - 加载标准输入缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394487/

相关文章:

c++ - Linux:使用管道标准输入/标准输出执行子进程

c - 如何从 C 中的矩阵打印排序列

networking - 自定义 TCP 服务中缓冲区使用和调整的一些技巧是什么?

c - 这种字符串检索方法有什么缺点吗?

c - 在 C 中迭代来自 stdin 的字符串

python - Python 子进程 PIPE 中的多个输入(使用标准输入或通信)

c - 如何以编程方式转换音频(diy)?

c - c中有多少种浮点类型?

java - 偶数、奇数和偶数消费者-生产者

python - 类型错误 : 'str' does not support the buffer interface 4