Manipulators in C
Manipulators in C
Manipulators are helping functions that can modify the stream. They
can be included in the I/O statement to alter the format parameters of a
stream. They are defined inside <iomanip> and some are also defined
inside <iostream> header file.
For example, if we want to print the hexadecimal value of 100 then we
can print it as:
cout << setbase(16) << 100
Types of Manipulators
There are various types of manipulators classified on the basis type of
entity they manipulate:
Table of Content
1. Output Stream Manipulators
Output stream manipulators are used to control and format the output
stream, such as setting the width, precision, or alignment of printed
data. They allow for a better presentation of output.
Following table lists some common output stream manipulators:
Header
Manipulator Description File
Example
#include <iostream> using namespace std;
int main() {
char c1, c2;
// Input skips whitespace by default
cin >> c1;
// Input the next character without skipping whitespace
cin >> noskipws >> c2;
cout << "c1: " << c1 << ", c2: " << c2;
return 0; }
3. Boolean Manipulators
Boolean manipulators are used to format boolean values in output.
They allow displaying boolean values as true or false or as 1 and 0,
depending on the requirement.
Example
#include <iostream>
int main() {
Example
#include <iostream> #include <iomanip> using namespace std;
int main() {
int n = 42;
// Align output to the left
cout << left << setw(10) << n << endl;
// Align output to the right
cout << right << setw(10) << n << endl;
// Show positive sign for numbers
cout << showpos << n << endl;
// Don't show positive sign for numbers
cout << noshowpos << n;
return 0; }
5. Base Manipulators
Base manipulators are used to format numbers in different bases, such
as decimal, hexadecimal, or octal. They help in representing numbers
in a way suited to specific applications.
Following table lists some common base manipulators:
Manipulator Description Header File
Example
#include <iostream> using namespace std;
int main() {
int n = 42;
// Output in hexadecimal base
cout << hex << n << endl;
// Output in decimal base
cout << dec << n << endl;
// Output in octal base
cout << oct << n;
return 0; }
Output
2a
42
52