In C++, put(c) writes exactly one character to an output stream. It does no formatting. Whatever character you give, that character appears.
The result is always a character, even if you pass a number. That makes it different from cout << number, which prints digits. Include <iostream> to use it.
This is a member function of std::ostream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call put on an output stream and pass one character.
C++
std::cout.put('A');
std::cout.put('B').put('\n'); // calls can be chained
Call
What it does
std::cout.put('A')
Writes the letter A.
std::cout.put(65)
Writes A too, because the number 65 is the code of A.
out.put('x').put('y')
Chains two writes. put() returns the stream.
For normal text use <<. put() is useful when you build output one character at a time.
Library declarations
C++
ostream& put(char_type ch);
Parameters
Parameter
Description
ch
Required. The character to write. A number is converted to the character with that code.
Return Value
Return Value
Description
ostream&
A reference to the stream. If the write failed, badbit is set.
C++ Examples
Example 1 — Write Characters with put()
Because put() returns the stream, you can chain calls.
C++
#include <iostream>
int main() {
std::cout.put('C').put('+').put('+').put('\n');
return 0;
}
Output
C++
How It Works
std::cout.put('C') writes C and returns std::cout.
The returned stream is used for the next put(), so + and + follow.
The last put('\n') writes a new line character, which moves the cursor to the next line.
Example 2 — Write a String One Character at a Time
Loop over a string and send each character with put(). Here each letter is made uppercase.
C++
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string word = "hello";
for (char c : word) {
std::cout.put(static_cast<char>(std::toupper(c)));
}
std::cout.put('\n');
return 0;
}
Output
HELLO
How It Works
The for loop visits every character of word.
std::toupper(c) gives the uppercase version, and put() writes just that one character.
After the loop, one more put('\n') ends the line.
Example 3 — put() with a Number
A number given to put() becomes a character. Compare it with <<.