Question

I'm trying to use C++ idioms to write a character to cout, but I can't find a character formatter in any of the C++ standard libraries.

Was it helpful?

Solution

Chars are automatically formatted like %c. To print integer as char (if you really want to), you can convert it:

int x = 42;
std::cout << (char) x;

Reading works similarly (it behaves similar to cout, not so much to scanf). No formatting required:

char c;
std::cin >> c;

Here is an echo example:

char c;
while(std::cin >> std::noskipws >> c) {
    std::cout << c;
}

One caveat with cin is that it is stateful. If you've already used cin in your code, you may need to reset the error-state bits with std::cin.clear()

OTHER TIPS

There are no formatters, there are different overloads of operator<<.

char c = 'a';
cout << c;
int i = 42;
cout << i;

If you just pass a char to an outstream, it will print as a char:

char a = 'a';
std::cout << a;

->

a

If you want to output an int as a char, you can cast it:

int i = 'i';
std::cout << static_cast<char>(i);

->

i

Can't find any formatters, but this works:

int c = 'x';

cout.put(c);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top