为什么通过cin的int8_t和用户输入显示奇怪的结果 [英] Why does int8_t and user input via cin shows strange result
问题描述
一小段代码让我发疯,但希望你可以阻止我跳出窗外。看这里:
A tiny piece of code drives me crazy but hopefully you can prevent me from jumping out of the window. Look here:
#include <iostream>
#include <cstdint>
int main()
{
int8_t i = 65;
int8_t j;
std::cout << "i = " << i << std::endl; // the 'A' is ok, same as uchar
std::cout << "Now type in a value for j (use 65 again): " << std::endl;
std::cin >> j;
std::cout << "j = " << j << std::endl;
if (i != j)
std::cout << "What is going on here?????" << std::endl;
else
std::cout << "Everything ok." << std::endl;
return 0;
}
如果我使用 int
而不是 int8_t
一切都好。我需要这个8位无符号整数
,而不是更大。顺便说一下。与 unsigned char
它的行为相同 - 当然 - 与 int8_t
一样。
If I use int
instead of int8_t
everything ok. I need this as 8-bit unsigned integers
, not bigger. And btw. with unsigned char
it's the same behaviour - of course - as with int8_t
.
任何有提示的人?
推荐答案
int8_t
是具有所需特征的整数类型的typedef:纯二进制补码表示,无填充位,大小正好为8位。
int8_t
is a typedef for an integer type with the required characteristics: pure 2's-complement representation, no padding bits, size of exactly 8 bits.
对于大多数(可能是全部)编译器,这意味着它将成为 signed char
的typedef。(由于术语有符号整数类型的定义中的怪癖,它不能是普通的 char
的typedef,即使 char
正好签名)。
For most (perhaps all) compilers, that means it's going to be a typedef for signed char
.(Because of a quirk in the definition of the term signed integer type, it cannot be a typedef for plain char
, even if char
happens to be signed).
>>
运算符专门处理字符类型。读取字符会读取单个输入字符,而不是表示十进制中某个整数值的字符序列。因此,如果下一个输入字符是'0'
,则读取的值将是字符值'0'
,大概是48。
The >>
operator treats character types specially. Reading a character reads a single input character, not sequence of characters representing some integer value in decimal. So if the next input character is '0'
, the value read will be the character value '0'
, which is probably 48.
由于 typedef
为现有类型创建别名,不是新的不同类型,>>
运算符无法知道您要处理 int8_t
作为整数类型而不是字符类型。
Since a typedef
creates an alias for an existing type, not a new distinct type, there's no way for the >>
operator to know that you want to treat int8_t
as an integer type rather than as a character type.
问题是在大多数实现中没有8位整数类型,它不是字符类型。
The problem is that in most implementations there is no 8-bit integer type that's not a character type.
唯一的解决方法是读入 int
变量,然后转换为 int8_t
(如果需要,可以进行范围检查)。
The only workaround is to read into an int
variable and then convert to int8_t
(with range checks if you need them).
顺便说一下, int8_t
是签名类型;相应的无符号类型是 uint8_t
,其范围为0..255。
Incidentally, int8_t
is a signed type; the corresponding unsigned type is uint8_t
, which has a range of 0..255.
(还有一个考虑因素:如果 CHAR_BIT> 8
,这是标准允许的,那么 int8_t
和 uint8_t
将被定义。)
(One more consideration: if CHAR_BIT > 8
, which is permitted by the standard, then neither int8_t
nor uint8_t
will be defined at all.)
这篇关于为什么通过cin的int8_t和用户输入显示奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!