Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different output while using std::cout and std::println

Tags:

c++

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
like image 699
Harry Avatar asked Feb 02 '26 21:02

Harry


2 Answers

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;
}
like image 200
463035818_is_not_a_number Avatar answered Feb 04 '26 10:02

463035818_is_not_a_number


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
like image 36
康桓瑋 Avatar answered Feb 04 '26 11:02

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!