Search code examples
c++fileifstreamofstream

C++ Syntax to enter values from code (like i from a loop) inside file name parenthesis for ofstream


I have a simple question, yet I can't find any documentation on it.. I'm trying to use ofstream and ifstream to read in file names with varying numbers, and output new files with those same numbers.

For example, if I have the files input1.txt, input2.txt, and input3.txt, and I need output1.txt, output2.txt, and output3.txt, I would do something like this:

for(i = 1; i <= 3; i++) {
ifstream fin("input"i".txt");
ofstream fout("output"i".txt");

... do stuff ...

fin.close();
fout.close()
}

Now, obviously this syntax for file names doesn't work. Does anyone have any idea how I could append on the number 1? Also I would need to append on other basic things, like one-word strings, etc.

Thanks in advance!


Solution

  • I'd probably just make two variables in the loop like this:

    std::string in = "input" + std::to_string(i) + ".txt";
    std::string out = "output" + std::to_string(i) + ".txt";