c - fgets 读取比应有的更多的字符

标签 c arrays string sizeof fgets

我正在开发一个代码,用户将键入几个段落,当用户以“END”开始段落时,它将停止阅读。代码将通过计算每个字母并显示图表和等等来操作字符串,但这与问题无关。 问题是:哪个段落不得超过 1000 个字符。

代码的较小版本如下(考虑到我只想存储 5 个字符的字符串 - 尽管我会扩展它)。

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

int main()
{
  char paragraph[5];

  for ( ; ; )
  {
    fgets(paragraph, 5, stdin);

    if (paragraph[0]=='E' && paragraph[1]=='N' && paragraph[2]=='D')
    { return 0; }

    printf("%s", paragraph);
  }

  return 0;

我的问题是:如果我输入超过5个字符,printf函数仍然打印超过5个字符,我不知道为什么。我已经检查了我能检查的所有内容。

请帮助像我这样的初学者。

最佳答案

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

因此,当输入超过 4 个字符(包括换行符)时,仅读取 4 个字符,其余字符保留在缓冲区中,准备下次 fgets 读取。

在这种情况下,您的 printf 将不会打印任何换行符,并且会被多次调用,使其看起来像打印超过 4 个字符。

按照评论中的建议,尝试 printf("[%s]", paragraph); 查看各个 printf 调用。

关于c - fgets 读取比应有的更多的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512839/

相关文章:

ios - 如何在结构定义中定义CGPoints数组?

python - 使用python解码tcp数据包

java - 需要帮助将输入从 String 拆分为 int

c - 打印常量字符串的推荐方法是什么?

c - 将指针重置为字符数组

php - mysql查询在php中存储字符串数组SQL语法错误

c++ - 为什么不允许通过检索到的指向其数据的指针来修改字符串?

c# - 读取蓝牙信号强度

c - Base 64解码在C中返回NULL

c - 为什么从 inptr 读入数组的值不同于 fgetc(inptr) 给出的值?