0

I need to use some integer values as a part of some file names I create as outputs in a c++ program. For this I use the code above. The thing is my int values ( named n_irrad in the code) goes from 1 to 20000 for example, so I need the file names to be MC_Interface00001.txt, MC_Interface00002.txt, ..., MC_Interface20000.txt. So, ¿how can I set the number of digits in the file name? With the code I'm using I obviously get MC_Interface1.txt, MC_Interface2.txt, ..., MC_Interface20000.txt.

Thanks in advance.

ofstream MC_Interface;
string Irrad = static_cast<ostringstream*>( &(ostringstream() << n_irrad) )->str();
string MC_Interface_FileName = "MC_Interface" + Irrad + ".txt";
MC_Interface.open(MC_Interface_FileName.c_str()); 
Pablo
  • 21
  • 4

2 Answers2

1

Try the following

#include <iostream>
#include <iomanip>
#include <sstream>

int main() 
{
    std::ostringstream os;

    os << std::setw( 5 ) << std::setfill( '0' ) << 10;

    std::string s = "MC_Interface" + os.str();
    std::cout << s << std::endl;

    return 0;
}

The output is

MC_Interface00010
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0
ofstream MC_Interface;
std::stringstream ss("MC_Interface");
ss << std::setw(5) << std::setfill('0') << n_irrad;
ss << ".txt";
MC_Interface.open(ss.str());