How can I dynamically name files in C++ using a string and integer?

  • Context: Comp Sci 
  • Thread starter Thread starter burritoloco
  • Start date Start date
  • Tags Tags
    Dynamic File
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
burritoloco
Messages
81
Reaction score
0
Hello,

I'm wondering how to name/open a file whose name is given by a string with an integer appended at the end, i.e., something in the style of the following. Thank you!

int i = 5;

ofstream fout;

string s = "Hello " + i;

fout.open(s);

// write something to the file

fout.close();
 
Physics news on Phys.org
I would take

Code:
char filename[32];

sprintf(filename,"name%i",i);

fout.open(filename);

route, but I am not convinced it is how it should be done in C++. I started with C and have tendency to code in C+.
 
Thank you. Worked perfectly.