0

I want to generate files which have a sequential numbers in their file names with numbers having same width (appended with zeros) like file names should be generated like below : File_001.txt File_002.txt ..... File_020.txt

`

int main()
{
for(int i=1; i<=20; i++)
{
std::string file = "File_"+std::to_string(i)+".txt";
}
}

`

With above code, file names generated are : File_1.txt ...... File_20.txt

But I want to generate file names as mentioned above

mascot
  • 141
  • 2
  • 9

2 Answers2

0

You need to use std::setfill and std::setw. Check this example:

#include <iomanip>
#include <iostream>

int main(){    
        for(int i = 0; i < 100; ++i){
                std::stringstream ss;
                ss << std::setfill('0') << std::setw(3);
                ss << i;
                std::string my_filename = ss.str();
                std::cout << my_filename << std::endl;
        }
}
0

Use a stringstream. A stringstream lets you do output to a string, and then regular I/O manipulators will let you add leading zeros.

#include <sstream>
#include <imanip>

int main()
{
    for (int i=1; i<=20; i++)
    {
        std::stringstring buffer;
        buffer << "File_" << std::setfill('0') << std::setw(3) << i << ".txt";
        std::string file = buffer.str();
        ...
    }
}
john
  • 85,011
  • 4
  • 57
  • 81