Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Manipulators in C++
3.
Types of Manipulators
3.1.
Manipulators without arguments
3.2.
2. Manipulators with arguments
4.
Manipulators without Arguments
4.1.
C++
5.
Manipulators with Arguments
5.1.
1. std::setw(int n)
5.2.
C++
5.3.
2. std::setfill(char c)
5.3.1.
Example
5.4.
C++
5.5.
3. std::setprecision(int n)
5.5.1.
Example
5.6.
C++
6.
Some Important Manipulators in <ios>
6.1.
1. setw() Function in C++
6.1.1.
Syntax
6.1.2.
Example:
6.2.
C++
6.3.
2. setfill() Function in C++
6.3.1.
Syntax
6.3.2.
Example
6.4.
C++
6.5.
3. setprecision() Function in C++
6.5.1.
Syntax
6.5.2.
Example:
6.6.
C++
7.
Non-parameterized Manipulators in C++
7.1.
Example for std::endl and std::noshowpos
7.2.
C++
7.3.
Additional Example with std::hex and std::showbase
7.4.
C++
8.
Frequently Asked Questions
8.1.
What is the benefit of using manipulators in C++?
8.2.
Can manipulators be used with any type of data?
8.3.
How do I choose between parameterized and non-parameterized manipulators?
9.
Conclusion
Last Updated: Jun 11, 2024
Easy

Manipulators in C++

Author Riya Singh
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

C++ provides a powerful feature called manipulators that allow you to control the formatting of input & output in your programs. Manipulators are special functions or objects that you can use with the “cin” & “cout” streams to change how data will be displayed or read. They help you format text, align values, & control the precision of numerical output. This helps us with better readability and representation of data. 

Manipulators in C++

In this article, we will discuss the different types of manipulators in C++ and how to use them.

Manipulators in C++

Manipulators in C++ are functions or objects that can be used with the insertion (<<) & extraction (>>) operators to modify the input or output format. They are defined in the <iomanip> header file, which stands for "input/output manipulators". Manipulators provide a convenient way to control the formatting of data without the need for explicit function calls or complex formatting strings.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Types of Manipulators

Manipulators in C++ can be categorized into two types: those that require arguments and those that do not. Let’s understand the difference between these two in detail below : 

Manipulators without arguments

These manipulators do not require any additional information to control the output stream. They are simple to use and can significantly alter the display of output without needing to specify any extra details. For example:

  1. std::endl: Inserts a newline character and flushes the output buffer.
     
  2. std::noshowpos: Turns off the display of the positive sign in front of positive numbers.
     
  3. std::uppercase: Ensures that hexadecimal and scientific notations are printed in uppercase.

2. Manipulators with arguments

These manipulators need specific values to perform their tasks. They provide greater control over how data is formatted. For example:

  1. std::setw(int n): Sets the field width for the next insertion operation.
     
  2. std::setfill(char c): Fills the remaining space with the specified character.
     
  3. std::setprecision(int n): Specifies the number of digits to display after the decimal point for floating-point values.

Manipulators without Arguments

Manipulators that do not require arguments are very easy to use & are invaluable for quick format changes in output streams. Let’s look at few examples to see how they work in C++ : 

Code Example for std::endl and std::noshowpos

  • C++

C++

#include <iostream>
using namespace std;

int main() {
cout << "Number without positive sign: ";
cout << noshowpos << 200 << endl; // Outputs: 200
cout << "New line after this message." << endl;
return 0;
}

Output

Number without positive sign: 200
New line after this message.


In this code:

  • std::noshowpos manipulator is used to output a number without a positive sign.
     
  • std::endl not only inserts a new line but also flushes the output buffer, ensuring that all output is written to the console immediately.
     

Note : These manipulators are very useful for managing the output display without needing additional parameters, which makes them very user-friendly & essential for fast adjustments in the output format whenever required.

Manipulators with Arguments

Manipulators that require arguments are used for more detailed control over how data is displayed in your output stream. Let’s see some examples for this : 

1. std::setw(int n)

This manipulator sets the field width for the next insertion to the output stream, making it useful for aligning columns of data.

Example:

  • C++

C++

#include <iostream>
#include <iomanip> // Required for std::setw
using namespace std;

int main() {
cout << left; // Align text to the left
cout << setw(10) << "Name" << setw(5) << "Age" << endl;
cout << setw(10) << "Ravi" << setw(5) << 23 << endl;
cout << setw(10) << "Unnati" << setw(5) << 22 << endl;
return 0;
}

Output

Name      Age  
Ravi      23   
Unnati    22   


In this example, std::setw is used to specify the width of each column, ensuring that the outputs "Name" and "Age", as well as the corresponding values, are neatly aligned.

2. std::setfill(char c)

This manipulator fills any unused spaces in the field width with a specified character.

Example

  • C++

C++

#include <iostream>
#include <iomanip> // Required for std::setfill
using namespace std;

int main() {
cout << setfill('-');
cout << setw(10) << "Name" << setw(5) << "Age" << endl;
cout << setw(10) << "Ravi" << setw(5) << 23 << endl;
cout << setw(10) << "Unnati" << setw(5) << 22 << endl;
return 0;
}

Output

------Name--Age
------Ravi---23
----Unnati---22


Here, std::setfill('-') is used to fill the extra spaces in the output with dashes, enhancing the visual structure of the displayed data.

3. std::setprecision(int n)

Sets the precision, or the number of significant digits, for floating-point output.

Example

  • C++

C++

#include <iostream>
#include <iomanip> // Required for std::setprecision
using namespace std;

int main() {
double pi = 3.141592653589793;
cout << "Default precision (6): " << pi << endl; // Default precision
cout << setprecision(10);
cout << "Precision set to 10: " << pi << endl;
return 0;
}

Output

Default precision (6): 3.14159
Precision set to 10: 3.141592654


This code snippet demonstrates how std::setprecision can be used to change the number of digits shown after the decimal point, allowing for more precise numerical representations.

Some Important Manipulators in <ios>

In the <ios> library, C++ offers many important and specialized manipulators that are used  for precise control over data formatting. Let's discuss a few parameterized manipulators:

1. setw() Function in C++

The setw() manipulator sets the width of the next output field, ideal for aligning columns in tabular outputs.

Syntax

std::setw(int width);

Example:

  • C++

C++

#include <iostream>
#include <iomanip> // Required for setw
using namespace std;

int main() {
cout << setw(10) << "Name" << setw(10) << "Age" << endl;
cout << setw(10) << "Ravi" << setw(10) << 23 << endl;
cout << setw(10) << "Unnati" << setw(10) << 22 << endl;
return 0;
}

Output

Name       Age
      Ravi        23
    Unnati        22


This example demonstrates the use of setw() to create a neatly aligned table of names and ages.

2. setfill() Function in C++

The setfill() manipulator fills the unused space in the specified field width with a provided character.

Syntax

std::setfill(char fillChar);

Example

  • C++

C++

#include <iostream>
#include <iomanip> // Required for setfill
using namespace std;

int main() {
cout << setfill('*');
cout << setw(10) << "Name" << setw(10) << "Age" << endl;
cout << setw(10) << "Ravi" << setw(10) << 23 << endl;
cout << setw(10) << “Unnati" << setw(10) << 22 << endl;
return 0;
}

Output

******Name*******Age
******Ravi********23
****Unnati********22


In this code, setfill('*') is used to fill the gaps with asterisks, enhancing the visual appeal of the table.

3. setprecision() Function in C++

The setprecision() manipulator sets the number of digits displayed after the decimal point for floating-point numbers.

Syntax

std::setprecision(int precision);

Example:

  • C++

C++

#include <iostream>
#include <iomanip> // Required for setprecision
using namespace std;

int main() {
double pi = 3.14159;
cout << "Default precision (6): " << pi << endl; // Default precision
cout << setprecision(4) << "Precision set to 4: " << pi << endl;
return 0;
}

Output

Default precision (6): 3.14159
Precision set to 4: 3.142


This example shows how setprecision() can be used to control the precision of floating-point numbers to tailor the output for specific needs.

Non-parameterized Manipulators in C++

Non-parameterized manipulators are simple to use and do not require additional arguments to function. They provide a convenient way to format the output directly, which eventually helps in the increases of readability and maintaining consistency. Let’s look at some of the examples which shows how to use them : 

Example for std::endl and std::noshowpos

  • C++

C++

#include <iostream>
using namespace std;

int main() {
cout << "Displaying numbers without a positive sign: ";
cout << noshowpos << 200 << endl; // Outputs: 200
cout << "This is the end of the line." << endl; // Outputs a new line and flushes the buffer
return 0;
}

Output

Displaying numbers without a positive sign: 200
This is the end of the line.


In this example:

  • std::noshowpos is used to remove the positive sign before positive numbers, which is useful for simplifying numeric displays.
     
  • std::endl inserts a newline and flushes the output stream, ensuring that all output is immediately visible.
     

Additional Example with std::hex and std::showbase

  • C++

C++

#include <iostream>
#include <iomanip> // Required for setprecision
using namespace std;

int main() {
double pi = 3.14159;
cout << "Default precision (6): " << pi << endl; // Default precision
cout << setprecision(4) << "Precision set to 4: " << pi << endl;
return 0;
}

Output

Default precision (6): 3.14159
Precision set to 4: 3.142


This code shows:

  • std::hex: Converts integer values into hexadecimal.
     
  • std::showbase: Ensures the output displays the number base (e.g., 0x for hex).

Note : Non-parameterized manipulators are important tools to use if anybody wants to make their program outputs look attractive, without complicating their code with additional parameters.

Frequently Asked Questions

What is the benefit of using manipulators in C++?

Manipulators make output management easier by allowing developers to format data directly within the output stream, enhancing readability and presentation without additional coding overhead.

Can manipulators be used with any type of data?

Yes, most manipulators can be used with various data types, but some are specific to numeric or textual data. For instance, std::setprecision is typically used with floating-point numbers.

How do I choose between parameterized and non-parameterized manipulators?

Use non-parameterized manipulators for quick and simple modifications. Choose parameterized manipulators when you need more control over the formatting, such as setting field widths or padding characters.

Conclusion

In this article, we talked about the concept of manipulators in C++. We learned that manipulators are special functions or objects that allow you to control the formatting of input & output operations. We discussed the two types of manipulators: manipulators without arguments & manipulators with arguments. We also saw some important manipulators, such as setw(), setfill(), setprecision(), & setbase(), with proper examples which show their usage. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Previous article
Ternary Operator in C++
Next article
Diamond Problem in C++
Live masterclass