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

  • Thread starter Thread starter burritoloco
  • Start date Start date
  • Tags Tags
    Dynamic File
Click For Summary
To dynamically name files in C++, concatenate a string with an integer using the `std::to_string` function or `sprintf`. The example provided shows how to create a filename by appending an integer to a string. Using `std::ofstream`, the file can be opened with the constructed filename. The approach is confirmed to work effectively in C++. This method is a valid way to handle file naming in C++.
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.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 14 ·
Replies
14
Views
4K
  • · Replies 16 ·
Replies
16
Views
2K
  • · Replies 3 ·
Replies
3
Views
5K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 13 ·
Replies
13
Views
3K