c - 在 C 中使用 fget 读取固定数量的字符

标签 c stdin fgets

我正在尝试使用 C 中的函数 fgets() 读取 8 个字符,并且必须是来自标准输入的 8 个字符。

到目前为止,我已经得到了这个

    char HEX[9];
    while (fgets(HEX, 8, stdin) != NULL)
    {
      if (HEX[8] == '\0')
      {
        printf("GOOD\n");
        break;
      }
      else
      {
        printf("Not 8 characters");
      }
    }

但是它不起作用。有任何想法吗?还尝试使用 if (strlen(HEX) > 8) 但两者都没有。

提前致谢。

最佳答案

来自手册页:

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 (aq\0aq) is stored after the last character in the buffer.

您只阅读了七个字符。

关于c - 在 C 中使用 fget 读取固定数量的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956844/

相关文章:

C - 使用 fgets() 填充通过循环迭代的结构数组。如何在同一行上打印这些值?

C:查找 file1 中的用户名是否存在于包含电子邮件的 file2 中

cURL 无法解析主机,但 Web 浏览器可以访问它

c - gcc : ‘asm’ operand has impossible constraints 中的扩展 asm

c - 如何针对第一个数组中的每个位置迭代多个数组并迭代第二个数组?

c++ - 从键盘读取输入

python - 将 Python 作为子进程调用时,我可以强制它以交互模式运行吗?

c - fread 或 fwrite 给出 "Bad file number"

c - fgets() 无法正常工作

php读写文件不保存前导空格