This post will discuss how to pad strings in C++.

1. Using std::setw

The std::setw manipulator is commonly used to set the field width in C++ output operations. It is declared in the header <iomanip>. We can use it with std::ostringstream to pad a string with leading zeros.

Download  Run Code

 
If you need to just print the padded string to the output stream, do like:

Download  Run Code

2. Using std::setfill

Another option is to use the std::ostringstream with the std::setfill function, which sets the specified character as the fill character for the stream.

Download  Run Code

3. Using string::insert

The string::insert(i, n, c) inserts n consecutive copies of character c into the string before index i. We can use it to add padding to a string, as shown below:

Download  Run Code

4. Using std::string constructor

Finally, we can use the string constructor to construct only the padding and then append/prepend padding to the original string using the + operator. Here’s what the code would look like:

Download  Run Code

That’s all about padding strings in C++.