In the below code I'm trying to print an unsigned char variable using std::cout and std::println. Using std::cout prints the character while std::println prints the ascii value.
Can somebody explain why I'm getting different output?
#include <iostream>
#include <print>
int main() {
const unsigned char a = 'A';
std::println("{}", a);
std::cout << a << std::endl;
}
Output
65
A
std::println formats the output according to "Standard format specification". Only char and wchar_t are formatted as characters. Other integer types are interpreted as integers. Note that char is either signed or unsigned, but in either case it is a type distinct from unsigned char and signed char.
operator<<(std::ostream&,...) on the other hand has overloads for signed char, unsigned char and char that all print the character.
You get expected output if you print a char:
#include <iostream>
#include <print>
int main() {
const char a = 'A';
std::println("{}", a);
std::cout << a << std::endl;
}
Unlike operator<<, std::println/std::format by default treats unsigned char/signed char as integers.
If you want to output it as a char, you need to explicitly specify the type option c, like ([format.string.std]):
const unsigned char a = 'A';
std::println("{}", a); // 65
std::println("{:c}", a); // A
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With