This post will discuss how to add leading zeros to a string in C++.

1. Using std::string constructor

A simple solution is to create a string consisting of all zeros of the required length using the std::string constructor. Then append the original string to it. Following is a C++ implementation of the same:

Download  Run Code

2. Using string::insert

The above solution creates a new string. To insert the leading zeros in the original string, consider using the string::insert function. Its usage is demonstrated below:

Download  Run Code

3. Using std::ostringstream

Another option is to use the std::setw manipulator with std::ostringstream to pad a string with leading zeros. This would need <sstream> and <iomanip> headers.

Download  Run Code

4. Using std::format

Starting with C++20, we can use the formatting library to add leading zeros to the string. It provides the std::format function in the header <format>. With C++17 and before, we can use the {fmt} library to achieve the same.

Download Code

That’s all about adding leading zeros to a string in C++.