C语言 使用 scanf 读取无符号字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14146434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using scanf for reading an unsigned char
提问by user1293997
I'm trying to use this code to read values between 0 to 255 (unsigned char).
我正在尝试使用此代码读取 0 到 255 ( unsigned char)之间的值。
#include<stdio.h>
int main(void)
{
unsigned char value;
/* To read the numbers between 0 to 255 */
printf("Please enter a number between 0 and 255 \n");
scanf("%u",&value);
printf("The value is %u \n",value);
return 0;
}
I do get the following compiler warning as expected.
我确实按预期收到了以下编译器警告。
warning: format ‘%u' expects type ‘unsigned int *', but argument 2 has type ‘unsigned char *'
And this is my output for this program.
这是我对这个程序的输出。
Please enter a number between 0 and 255 45 The value is 45 Segmentation fault
I do get the segmentation fault while running this code.
运行此代码时,我确实遇到了分段错误。
What is the best way to read unsigned charvalues using scanf?
unsigned char使用读取值的最佳方法是什么scanf?
回答by Joe
The %uspecifier expects an integer which would cause undefined behavior when reading that into a unsigned char. You will need to use the unsigned charspecifier %hhu.
该%u说明符需要一个整数读取到时会导致不确定的行为unsigned char。您将需要使用说明unsigned char符%hhu。
回答by grenix
For pre C99 I would consider writing an extra function for this just alone to avoid that segmentation fault due to undefined behaviour of scanf.
对于 C99 之前的版本,我会考虑单独为此编写一个额外的函数,以避免由于 scanf 的未定义行为而导致的分段错误。
Approach:
方法:
#include<stdio.h>
int my_scanf_to_uchar(unsigned char *puchar)
{
int retval;
unsigned int uiTemp;
retval = scanf("%u", &uiTemp);
if (retval == 1)
{
if (uiTemp < 256) {
*puchar = uiTemp;
}
else {
retval = 0; //maybe better something like EINVAL
}
}
return retval;
}
Then replace scanf("%u",with my_scanf_to_uchar(
然后替换scanf("%u",为my_scanf_to_uchar(
Hope this is not off topic as I still used scanfand not another function like getchar:)
希望这不是题外话,因为我仍在使用,scanf而不是像getchar:)这样的其他功能
Another approach (without extra function)
另一种方法(没有额外的功能)
if (scanf("%u", &uiTemp) == 1 && uiTemp < 256) { value = uitemp; }
else {/* Do something for conversion error */}

