Reputation: 24632
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.
Upvotes: 0
Views: 171
Reputation: 238401
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()
Upvotes: 2
Reputation: 5118
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
Upvotes: 1
Reputation: 55415
There are no formatters, there are different overloads of operator<<
.
char c = 'a';
cout << c;
int i = 42;
cout << i;
Upvotes: 2
Reputation: 24632
Can't find any formatters, but this works:
int c = 'x';
cout.put(c);
Upvotes: 0