问题
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?
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.
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.
回答1:
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.
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;
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);
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);
回答2:
As things go, this is a reasonable use of casts, but yes it can be improved. The "loss of integrity" involved is simply that if one of the data types changes from char to say double the cast will continue to compile but probably not do what you want. You can create a helper function instead:
inline int to_int(char c) { return static_cast<int>(c); }
Unlike the static_cast, this will only kick in when the original type is char
, so if you changed to something like double
you'd get a compiler warning - effectively a reminder to review your code.
来源:https://stackoverflow.com/questions/11236759/displaying-chars-as-ints-without-explicit-cast