Search⌘ K

Format Specifier

Explore how to modify input and output data in C++ using format specifiers presented as manipulators. Understand aligning text, displaying boolean values, setting field widths, and formatting numbers in decimal, octal, or hexadecimal. Learn to control floating point precision and display styles to optimize program output.

We'll cover the following...

Format specifiers enable us to adjust the input and output data explicitly.

ℹ️ We use manipulators as format specifiers
The format specifiers are available as manipulators and flags. We only present manipulators in this course because their functionality is quite similar and manipulators are more comfortable to use.

C++
#include <iostream>
int main(){
std::cout << std::endl;
int num{2011};
std::cout << num << "\n\n";
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout << num << std::endl;
std::cout.setf(std::ios::dec, std::ios::basefield);
std::cout << num << std::endl;
std::cout << std::endl;
std::cout << std::hex << num << std::endl;
std::cout << std::dec << num << std::endl;
std::cout << std::endl;
}

The following tables present the important format specifiers. They are sticky except for the field width, which is reset after each application.

The manipulators without any arguments require the header <iostream>, and the manipulators with arguments require the header <iomanip>.

Manipulator Stream type Description
std::boolalpha input and output Displays the boolean as a word.
std::noboolalpha input and output Displays the
...