• Home
  • Manipulators in C++ with Examples

Manipulators in C++ with Examples

Manipulators are special functions or objects that are used in C++ to modify the output stream when printing data to the screen or writing it to a file. There are several manipulators available in C++, including the following:

std::endl: The std::endl manipulator is used to insert a newline character at the end of the output. It also flushes the output buffer, which means it forces any buffered output to be written to the screen or file immediately.

#include <iostream>

int main()
{
std::cout << "Line 1" << std::endl;
std::cout << "Line 2" << std::endl;
return 0;
}

This code will output the following:

Line 1
Line 2
std::flush: The std::flush manipulator is used to flush the output buffer without inserting a newline character.
#include <iostream>

int main()
{
std::cout << "Line 1" << std::flush;
std::cout << "Line 2" << std::endl;
return 0;
}

This code will output the following:

Line 1Line 2
std::hex: The std::hex manipulator is used to set the output stream to print numbers in hexadecimal format.
#include <iostream>

int main()
{
int x = 255;
std::cout << x << std::endl;
std::cout << std::hex << x << std::endl;
return 0;
}

This code will output the following:

255
0xff
std::dec: The std::dec manipulator is used to set the output stream to print numbers in decimal format.
#include <iostream>

int main()
{
int x = 255;
std::cout << std::hex << x << std::endl;
std::cout << std::dec << x << std::endl;
return 0;
}

This code will output the following:

0xff
255
std::setw: The std::setw manipulator is used to set the width of the output field for a variable.
#include <iostream>

int main()
{
int x = 255;
std::cout << std::setw(10) << x << std::endl;
return 0;
}

This code will output the following:

255
std::setfill: The std::setfill manipulator is used to set the fill character for an output field.

 

#include <iostream>

int main()
{
int x = 255;
std::cout << std::setw(10) << std::setfill('0') << x << std::endl;
return 0;
}