What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Manipulators in C++ Explained (with Examples)

  • Sep 04, 2023
  • 6 Minute Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abrar Ahmed
Manipulators in C++ Explained (with Examples)

Whether you're a beginner or an experienced programmer, understanding manipulators will elevate your C++ programming skills and enable you to present your data in an elegant and readable manner.

What are C++ Manipulators?

In the realm of C++ programming, manipulators play a vital role in enhancing the aesthetics of output formatting.  They are powerful tools that enable developers to control various aspects of how data is presented on the screen or in files.

C++ Manipulators are functions or objects that can modify the output behavior of standard stream objects, such as 'cout' and 'cin'. They are used to modify the formatting of data including field width, precision, alignment, padding, and more.

Manipulators can be applied directly to the output stream using the insertion operator (<<) to modify the formatting of subsequent output. Let's dive into some practical examples to better understand how they work:

#include
#include 

int main() {

int num = 1234;

double pi = 3.14159;

std::cout << "Default: " << num << std::endl;

std::cout << "Fixed width: " << std::setw(10) << num << std::endl;

std::cout << "Precision: " << std::setprecision(3) << pi << std::endl;

return 0;

}  

 

In the above code, we include the `` and `` headers, which provide the necessary functionality for working with manipulators. We then use the `std::setw()` manipulator to set the field width to 10 for the variable `num`. Learn more about setw() function in C++ here.

This ensures that the output is padded with spaces to maintain a consistent width. Additionally, we use the `std::setprecision()` manipulator to set the precision to 3 decimal places for the variable `pi`. This allows us to control the level of detail in our output.

Types of Manipulators in C++

C++ provides a range of manipulators to suit different formatting needs. Some common types of manipulators include:

  1. `std::setw(n)`: Sets the field width to n characters.
  2. `std::setprecision(n)`: Sets the precision (number of decimal places) to n.
  3. `std::fixed`: Forces decimal representation for floating-point numbers.
  4. `std::scientific`: Forces scientific notation for floating-point numbers.
  5. `std::setfill(c)`: Sets the fill character to c for padding.

Why are they used?

Manipulators in C++ provide a convenient way to control the formatting of output, making it more readable and visually appealing. Manipulators allow for consistent presentation of data across different platforms and systems. They also aid in aligning data in columns, adjusting precision, controlling the base representation of numbers, and more.

Parameterized Manipulators in C++

In addition to the built-in manipulators provided by C++, it is also possible to create custom manipulators tailored to specific needs. Parameterized manipulators are functions that take additional arguments to modify the formatting behavior.

For example, let's create a parameterized manipulator to display a number with a specific number of leading zeroes:

#include 
#include 

std::ostream& leadingZero(std::ostream& os, int width) {

os << std::setfill('0') << std::setw(width);

return os;

}

int main() {

int num = 42;

std::cout << leadingZero << num << std::endl;

return 0;

}

 

In the code snippet above, we define a custom manipulator function called 'leadingZero' that takes the desired width as an argument. It sets the fill character to '0' and the field width to the specified value. We can then apply this manipulator to the output stream `std::cout` using the insertion operator (<<) to display the number with leading zeroes.

User-Defined Manipulators

Apart from parameterized manipulators, C++ allows for the creation of user-defined manipulators without any parameters. These manipulators can perform any desired formatting operation.

For instance, let's create a user-defined manipulator that converts a number to uppercase:

#include 
#include 
#include 

std::ostream& uppercase(std::ostream& os) {

std::string str;

std::getline(os, str);

for (char& c : str) {

c = std::toupper(c);

}

os << str;

return os;

}

int main() {

std::cout << uppercase << "hello, world!" << std::endl;

return 0;

}  

 

In the above code, the `uppercase` manipulator reads the input string from the output stream `std::cout` using `std::getline()`. It then converts each character to uppercase using `std::toupper()` and outputs the modified string back to the stream.

Conclusion

By leveraging manipulators, developers can enhance the readability and structure of their code's output. Need to use them in your assignment or project? Get Expert Help for C++ online from top experts!

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abrar Ahmed
An ambivert individual with a thirst for knowledge and passion to achieve. Striving to connect Artificial Intelligence in all aspects of life. I am also an avid coder and partake in coding challenges all the time on Leetcode and CodeChef.