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
Click For Summary
SUMMARY

The discussion focuses on dynamically naming files in C++ by appending an integer to a string. The user initially attempts to concatenate a string and an integer directly, which is not valid in C++. The correct approach involves using the sprintf function to format the filename, as demonstrated with char filename[32]; sprintf(filename,"name%i",i);. This method successfully creates a filename that can be opened with ofstream.

PREREQUISITES
  • Understanding of C++ file handling with ofstream
  • Familiarity with string manipulation in C++
  • Knowledge of the sprintf function for string formatting
  • Basic understanding of C++ syntax and data types
NEXT STEPS
  • Explore C++ string streams for dynamic file naming
  • Learn about C++11 std::to_string for converting integers to strings
  • Research error handling in file operations using ofstream
  • Investigate best practices for managing file paths in C++
USEFUL FOR

C++ developers, programmers transitioning from C to C++, and anyone looking to enhance their file handling techniques 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 16 ·
Replies
16
Views
3K
  • · Replies 14 ·
Replies
14
Views
4K
  • · 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
3K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 13 ·
Replies
13
Views
3K