SCANF为什么将第一个值设置为0?

发布于 2025-02-02 20:50:21 字数 441 浏览 3 评论 0原文

我正在使用scanf获取输入。但是,当我运行此代码时:

#include<stdio.h>

int main(){
  unsigned char in,b;
  scanf("%u %u",&in,&b);
  printf("%u %u\n",in,b);
  return 0;
}

例如,当我输入12 3时,输出为0 3

当我而不是scanf(“%u%u”,&amp; in,&amp; b); write scanf(“%u”,&amp; in); scanf( “%u”,&amp; b);

感谢您伸出援手。

I am using scanf to get an input. But when I run this code:

#include<stdio.h>

int main(){
  unsigned char in,b;
  scanf("%u %u",&in,&b);
  printf("%u %u\n",in,b);
  return 0;
}

when I input, for example, 12 3 , the output is 0 3.

This also happends when I instead of scanf("%u %u",&in,&b); write scanf("%u",&in);scanf("%u",&b);.

Thanks for reaching out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月亮是我掰弯的 2025-02-09 20:50:21

SCANF的这种调用

unsigned char in,b;
scanf("%u %u",&in,&b);

调用了未定义的行为,因为该功能期望其第二和第三个参数是对intemed int的对象的指示,而实际上它们是对Unsigned char 。

相反,您必须使用转换说明器u

scanf("%hhu %hhu",&in,&b);

从C标准(7.21.6.2 FSCANF函数)

使用长度修饰符hh

11长度修饰符及其含义是:

hh 指定以下d,i,o,u,x,x,x,x,x或n转换指定符适用于带有类型指针指向签名char 的参数
无符号char

This call of scanf

unsigned char in,b;
scanf("%u %u",&in,&b);

invokes undefined behavior because the function expects that its second and third arguments are pointers to objects of the type unsigned int while actually they are pointers to objects of the type unsigned char.

Instead you have to use the length modifier hh with the conversion specifier u

scanf("%hhu %hhu",&in,&b);

From the C Standard (7.21.6.2 The fscanf function)

11 The length modifiers and their meanings are:

hh Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to signed char
or unsigned char.

轻拂→两袖风尘 2025-02-09 20:50:21

作为补充,如果%hhu不可用的转换说明符,您可以做:

#include<stdio.h>
unsigned char inp_u8(void){
    unsigned int x;
    scanf("%u",&x);
    return x&0xFF;
}

Just as an addition, in case of the %hhu conversion specifier being unavailable, you can do:

#include<stdio.h>
unsigned char inp_u8(void){
    unsigned int x;
    scanf("%u",&x);
    return x&0xFF;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文