【问题标题】:Reading in exactly N bytes from standard input in C从 C 中的标准输入中准确读取 N 个字节
【发布时间】:2021-04-09 01:34:21
【问题描述】:

我必须从标准输入中准确读取 4 个字节,然后将其视为小端序并在标准输出上显示,但我不知道我读取的内容是否正好是 4 个字节。我试过这个:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <byteswap.h>

int main() {
   uint32_t f;

   printf("Enter a value :");
   scanf ("%" SCNu32, &f);
   printf("Value of integer:%d", f);
   //printf("Value of integer:%d", __bswap_32(f));

   return 0;
}

我不确定这是否准确读取 4 个字节。我尝试了以下整数:

input->output
123->123
12345678->12345678
123456789->123456789
4294967295->-1
4294967294->-2
4294967296->-1
1->1

我认为通过打印f 会像这样:1234000f=1234 的值)或12345678f=123456789 的值)。

【问题讨论】:

  • %d 打印一个签名 int,试试%u
  • 我刚刚尝试过%u 和它一样。
  • 你的意思是你还在得到4294967295 -> -1%u不能输出负值。目前还不是很清楚你要做什么。
  • 对不起,你是对的!我尝试使用123456789 而不是4294967295。如果我尝试使用4294967296,我仍然会得到4294967295,我认为这是正确的。谢谢!

标签: c byte bit uint32-t


【解决方案1】:

要从stdin 中准确读取4 个字节,您可以使用fread()getc()scanf()

  • fread(&amp;f, sizeof f, 1, stdin);
  • char *p = (char *)&amp;f; for (size_t i = 0; i &lt; sizeof(f); i++) p[i] = getchar();
  • char *p = (char *)&amp;f; for (size_t i = 0; i &lt; sizeof(f); i++) p[i] = getc(stdin);
  • char *p = (char *)&amp;f; scanf("%c%c%c%c", p, p+1, p+2, p+3);

但请注意,在执行换行符的旧系统上,stdin 默认以文本模式打开,并且没有可移植的方式在打开的流上更改此模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2012-04-25
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多