c - A problem with the behaviour of scanf when data type is unsigned char
问题描述
So I have no idea why this behavior is observed:
#include <stdio.h>
int main()
{
unsigned char c;
char d;
scanf("%hhu", &d);
printf("%c\n", d);
return 0;
}
If I remember correctly %hhu
is for unsigned char
. If I input almost any character like a
, or b
the answer is nothing and d
gets the value 0
. But if I input 97
then d
prints the value a
(so ASCII is converted to char). This clearly not the case when the data type is char
. I can just input the character directly and it is stored.
Also in the slight modification of this code
#include <stdio.h>
int main()
{
unsigned char c;
char d;
int g;
scanf("%hhu", &d);
printf("%c\n", d);
scanf("%d", &g);
printf("%d is g\n", g);
return 0;
}
If I give first input as a character like w
or a
then it just skips the second scanf
, but if the input is a number then it works normally.
解决方案
您是正确的,%hhu
格式说明符需要一个unsigned char*
参数。但是,u
格式的一部分规定将输入解释为十进制整数。要将数据作为(未处理的)字符输入,您应该使用%c
格式说明符。
推荐阅读
- php - Laravel - 将多个数组作为新行插入?
- typescript - 如何以角度展平嵌套的 formGroups
- database - 使用带有查询、数据可视化、dax 的 Power BI 中的 dax 表达式显示数据
- php - 找不到类“Spatie\YamlFrontMatter\YamlFrontMatter”
- php - Google Drive 访问令牌自动化
- html - Angular 在取决于垫选择的输入中显示不同的占位符
- javascript - 在Javascript中过滤两个日期之间的数据
- http - Apache camel 3.6 如何从目标 HTTP 端点 URL 中删除骆驼 http 参数
- delphi - ADOConnection ADOQuery CommandTimeout,覆盖顺序(如果有的话)
- javascript - 如何在 localStorage 中正确存储新数据对象并使用 NextJS 保留旧数据?