[英]Assign a value to char/unsigned char
How can i assign a value to a char/unsigned char?如何为 char/unsigned char 赋值? I tried to do it with this code
我试着用这段代码来做
#include <iostream>
int main() {
char a;
unsigned char b;
std::cout << "Enter a and b: " << std::endl;
std::cin >> a >> b;
std::cout << a << ":" << b << std::endl;
}
but it's printing only first two characters of variable a (i know that char can be one byte value, but i don't know why it doesn't want to accept my number and split it if it's bigger than 9)但它只打印变量a 的前两个字符(我知道 char 可以是一个字节值,但我不知道为什么它不想接受我的数字并在它大于 9 时将其拆分)
i know that char can be one byte value, but i don't know why it doesn't want to accept my number and split it if it's bigger than 9
我知道 char 可以是一个字节值,但我不知道为什么它不想接受我的数字并在它大于 9 时将其拆分
There seems to be a misundertanding here.这里好像有误会。
A char
can hold a byte but when you use一个
char
可以保存一个字节,但是当你使用
std::cin >> a;
only one character is read into a
, not the integer value that reprsents a byte.只有一个字符被读入
a
,而不是代表一个字节的 integer 值。
If your input is 95
, only the digit '9'
, not the integer value 95
, is read into a
.如果您的输入是
95
,则只有数字'9'
,而不是 integer 值95
,被读入a
。
Had a
been a variable of type int
,如果
a
是int
类型的变量,
std::cin >> a;
would read 95
into a.将
95
读入 a。 Of course, then there won't be the need for当然,以后就不需要了
std::cin >> a >> b;
That will expect the input for a
and the input for b
to be separated by one or more whitespace characters.这将期望
a
的输入和b
的输入由一个或多个空格字符分隔。
You can convert the int
to a char
by simply assigngment or explicit casting.您可以通过简单的赋值或显式转换将
int
转换为char
。
int i;
char a;
std::cin >> i; // Provide 95 as input.
a = i; // a is now the character that corresponds to 95 in the
// encoding used in your platform.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.