在vs编译器中,如何将0-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;
}

g++:

有警告(warning: format ‘%u’ expects type ‘unsigned int *’, but argument 2 has type ‘unsigned char *’),运行成功。

vs2008:

run-time check failure #2:stack around variable 'value' was corrupted.

将代码中的%u改为%hhu后:

g++:

没有警告,运行成功。

vs2008:

依然是run-time check failure #2:stack around variable 'value' was corrupted.

好像vs编译并不识别输入格式中h这个符号,将%hhu等同于%u(个人猜测)。

问题:

在vs编译器中,如何将0-255的整数读入unsigned char?

参考资料:
http://www.cnblogs.com/ayanmw...


补充

@kostring
你的代码在我的vs2008上运行结果:
图片描述

阅读 3.6k
3 个回答

在vs2008中亲测%hhu没问题:

    unsigned char ch;
    printf("get char:  ");
    scanf("%hhu", &ch);

    printf("what we get: %hhu, %c\n", ch, ch);
    return 0;

输出:
get char: 20
what we get: 20, ¶

我在vs2015试了下

unsigned char i;
scanf("%hhu", &i);

并没有报错可以运行的
还有在vs里用scanf_s比较好

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进