显示chars作为ints没有显式强制转换 [英] Displaying chars as ints without explicit cast
问题描述
每次向cout对象发送一个字符时,除非将其转换为int,否则它将以ASCII字符显示。
Every time I send a char to the cout object, it displays in ASCII characters unless I cast it to an int.
>有没有一种方法来显示一个字符的数值没有显式转换?
Q: Is there a way to display the numerical value of a char without an explicit cast?
我读到某处,在代码中执行太多的转换可能会导致损失诚信(你的程序)。我猜,字符显示在ASCII为特定的原因,但我不知道为什么。
I read somewhere that doing too many casts in your code could lead to a loss of integrity (of your program). I am guessing that chars display in ASCII for a particular reason, but I'm not sure why.
我基本上创建一个游戏。我使用小数字(unsigned chars),我打算显示在控制台。我可能是偏执的,但是当我在我的代码中的任何地方发出垃圾邮件 static_cast< int>
时,我得到这种不安的感觉。
I am essentially creating a game. I am using small numbers (unsigned chars) that I plan to display to the console. I may be paranoid, but I get this uneasy feeling whenever I spam static_cast<int>
everywhere in my code.
推荐答案
但是,类型转换没有什么问题,特别是如果你使用 static_cast
这就是你应该使用。
There is nothing wrong with type-casting, though, especially if you use static_cast
to do it. That is what you should be using. It allows the compiler to validate the type-cast and make sure it is safe.
要改变<< 的行为, code>运算符,您必须覆盖
char
值的默认<<
:
To change the behavior of the <<
operator, you would have to override the default <<
operator for char
values, eg:
std::ostream& operator <<(std::ostream &os, char c)
{
os << static_cast<int>(c);
return os;
}
char c = ...;
std::cout << c;
您可以创建一个自定义类型,它采用 char
作为输入,然后为该类型实现<
运算符,例如:
You could create a custom type that takes a char
as input and then implement the <<
operator for that type, eg:
struct CharToInt
{
int val;
CharToInt(char c) : val(static_cast<int>(c)) {}
};
std::ostream& operator <<(std::ostream &os, const CharToInt &c)
{
os << c.val;
return os;
}
char c = ...;
std::cout << CharToInt(c);
你可以创建一个类似的函数,然后你不必重写< <$ / code>运算符,例如:
You could create a function that does something similar, then you don't have to override the <<
operator, eg:
int CharToInt(char c)
{
return c;
}
char c = ...;
std::cout << CharToInt(c);
这篇关于显示chars作为ints没有显式强制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!