要将数字打印为字符,您可以将其分配给char
变量或将其强制转换为char
类型:
unsigned int value = 0x5B;
char c = static_cast<char>(value);
cout << "The character of 0x5B is '" << c << "` and '" << static_cast<char>(value) << "'\n";
你也可以使用snprintf
:
char text_buffer[128];
unsigned int value = 0x5B;
snprintf(&text_buffer[0], sizeof(text_buffer),
"%c\n", value);
puts(text_buffer);
示例程序:
#include <iostream>
#include <cstdlib>
int main()
{
unsigned int value = 0x5B;
char c = static_cast<char>(value);
std::cout << "The character of 0x5B is '" << c << "` and '" << static_cast<char>(value) << "'\n";
std::cout << "\n"
<< "Paused. Press Enter to continue.\n";
std::cin.ignore(1000000, '\n');
return EXIT_SUCCESS;
}
输出:
$ ./main.exe
The character of 0x5B is '[` and '['
Paused. Press Enter to continue.