I'm trying to use an integer value to its corresponding ASCII character:
char c = char(65); //65 equivalent to A character
MessageBox::Show(System::Convert::ToString(c), "Conversion",
MessageBoxButtons::OK, MessageBoxIcon::Error);
This method just displays "65" in the message box rather than the character A. Is there any way of displaying the character instead of the number in C++/CLI? I've tried multiple other methods but they don't seem to work.
This is an issue where the C++ and .Net types don't match up the way you expect them to.
In .Net, there is a distinct type for characters: System::Char
, or just Char
if you have using namespace System;
. (Note the capital "C", it's important.) This is a distinct type from System::UInt16
or System::Int16
, even though it's the same size.
In C++, char
and unsigned char
are the smallest types. There is no distinction between a one-byte character vs. a one-byte integer.
When mapping C++ types onto .Net types, char
maps to System::Byte
, which is a numeric type. That's why you're getting a string containing the word "65" in your conversion.
If you want something that .Net recognizes as a character, not a number, then you need to cast to Char
(with the capital "C" to make it System::Char
). Then you can call .ToString()
to get "A" instead of "65".
My test program:
int main(array<String^>^ args)
{
char native = (char)65;
Debug::WriteLine(native.ToString());
Char c = (Char)65;
Debug::WriteLine(c.ToString());
return 0;
}
Result:
65 A