c - 通常 gets() 将输入视为\n,位于其上方 printf() 的末尾

标签 c newline fgets gets

为什么 gets() 在这里要求字符串。我的意思是,为什么它不消耗前一个 printf() 中的换行符并且程序只是终止? 是的,我知道我应该使用 fgets() 之类的东西。请不要提及此事。

引用代码-

#include <stdio.h>

main()
{
    char str[30];
    printf("\n");
    gets(str);
    puts(str);
}

最佳答案

摘自char *gets(char *str)手册:

Reads a line from stdin and stores it into the string pointed to by, str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.

摘自 printf 手册:

The functions printf() and vprintf() write output to stdout, the standard output stream;

正如手册中提到的,getsstdin 读取一行。

函数printf写入stdout

因此 gets 不会读取 printf 正在写入的内容。

关于c - 通常 gets() 将输入视为\n,位于其上方 printf() 的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33207728/

相关文章:

c - C 列中连续 1 的最短数量

c - 从二维数组切换到一维(字符串)

c - 使用 getline 与 fgets 进行基本文件打印

c - fgets 函数被完全忽略

c - fgets 正在从关闭的文件描述符中读取更多数据

c - fgets不能完全填充数组

c - 修改c中文件的现有内容

python - 在 Python 中从一个文件读取和写入一个新行到另一个文件

C++ - 如何删除打印到控制台的换行符

java - 在 sql 查询中添加换行符 (\n) 是否安全?