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::printlnfunction requires format controls to tell it what type each parameter is. Since you have not provided any it will treat the value as an integer. Thestd::cout<<operator is overloaded for each object type, so it knows thatais a character.printlnmakes more sense to me, sinceunsigned charis a general-purpose integer type, not necessarily a character.std::println"knows" as well thatais aunsigned char, it just treats it differentlystd::cout << +a << std::endl;to get that output to match thestd::println. (Note thatstd::endlprobably should be"\n". There is no reason to do the extra work in this situation.)