用 scanf 读取小整数 [英] Reading small int with scanf

查看:58
本文介绍了用 scanf 读取小整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用 scanf 读取小整数(即范围 -128..127 的 1 字节整数)?考虑以下代码:

Is there a way to read a small int (i.e. 1-byte int of range -128..127) using scanf? Consider this code:

char x;
scanf("%d", &x);

程序将读取一个 int,很可能是 4 个字节,并尝试将其写入 x 的地址,从而违反了该地址之后进入内存的 3 个字节.

The program will read an int, most probably 4 bytes, and try to write it at the address of x, thus violating the 3 bytes which come in the memory after this address.

我知道有一个用于短整数 (%h) 的修饰符,但我还没有听说过用于小整数 (char) 的修饰符?

I know there is a modifier for short int (%h), but I haven't heard about one for small int (char) ?

推荐答案

scanf 需要 "%hhd" 格式字符串读入 char>.

scanf needs "%hhd" format string to read into a char.

这篇关于用 scanf 读取小整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆