3

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
6
  • 2
    The std::println function 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. The std::cout << operator is overloaded for each object type, so it knows that a is a character. Commented Nov 10 at 9:23
  • 3
    Because they are made differently? The behavior of println makes more sense to me, since unsigned char is a general-purpose integer type, not necessarily a character. Commented Nov 10 at 9:29
  • I believe if you remove unsigned you will get char in the output Commented Nov 10 at 9:32
  • 2
    @OldBoy std::println "knows" as well that a is a unsigned char, it just treats it differently Commented Nov 10 at 9:37
  • std::cout << +a << std::endl; to get that output to match the std::println. (Note that std::endl probably should be "\n". There is no reason to do the extra work in this situation.) Commented Nov 10 at 14:03

2 Answers 2

15

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;
}
Sign up to request clarification or add additional context in comments.

Comments

9

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.