[英]Why does std cin work only when used with int variable?
I'm trying to use std::cin after a while.一段时间后我尝试使用 std::cin 。
uint8_t
or unsigned char
:使用uint8_t
或unsigned char
:unsigned char data;
std::cin >> std::dec >> data;
Whatever std::dec
is used or not, I get the first ASCII character I type.无论是否使用std::dec
,我都会得到我输入的第一个 ASCII 字符。 If I type 12
, data is 0x31
not 12
.如果我输入12
,数据是0x31
而不是12
。 Why can't it parse number until 255
to be stored in a char
?为什么它不能解析直到255
数字才能存储在char
?
int data;
std::cin >> std::dec >> data;
gives correctly data=12/0xC
not 0x31
给出正确的data=12/0xC
而不是0x31
char[N]
with std::hex
将char[N]
与std::hex
char data[128];
std::cin >> std::hex >> data;
Also gets the ASCII characters instead of the hexadecimal.还获取 ASCII 字符而不是十六进制。
Writting 0x010203040506...
data is 0xFFFFFFFFF..
. 0x010203040506...
数据是0xFFFFFFFFF..
。
Isn't std::cin>>std::hex
able to parse the string I type into hexadecimal automatically? std::cin>>std::hex
不能自动解析我输入的字符串为十六进制吗?
In short:简而言之:
cin >> charVar
scans a single character from stdin
cin >> charVar
从stdin
扫描单个字符cin >> intVar
scans characters from stdin
until a non-numeric character is entered cin >> intVar
从stdin
扫描字符,直到输入非数字字符Explaining your observation:解释你的观察:
A char
variable can store a single ASCII character. char
变量可以存储单个 ASCII 字符。
When you type 12
, only the character 1
is scanned.当您键入12
,只会扫描字符1
。
The ASCII code of the character 1
is 0x31
.字符1
的 ASCII 码是0x31
。
std::dec
and std::hex
affect the format of integers. std::dec
和std::hex
影响整数的格式。
But as far as the streaming operators are concerned, char
and its variants (including uint8_t
aren't integers, they're single characters. They will always read a single character, and never parse an integer.但是就流操作符而言, char
及其变体(包括uint8_t
不是整数,它们是单个字符。它们将始终读取单个字符,并且从不解析整数。
That's just how these functions are defined.这就是这些函数的定义方式。 There is no way around it.没有其他办法了。 If you want an integer with a limited range, first read into an int
(or other integer type that is not a char
variant), and then range-check afterwards.如果你想要一个范围有限的整数,首先读入一个int
(或其他不是char
变体的整数类型),然后再进行范围检查。 You can, if you want, cast it to a small type afterwards, but you probably shouldn't.如果您愿意,您可以在之后将其转换为小类型,但您可能不应该这样做。 char
types are awkward to work with numerically. char
类型在数字上处理起来很尴尬。
Similarly, reading into an array of char
reads a string.类似地,读入一个char
数组读取一个字符串。 (Also, never do that without using setw()
to limit the length to fit in the buffer you have. Better yet, use std::string
instead.) That's just how it's defined. (另外,在不使用setw()
限制长度以适合您拥有的缓冲区的情况下,永远不要这样做。更好的是,使用std::string
代替。)这就是它的定义方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.