I'm trying to write a code that will output to a list of files text which is almost identical, apart from that file's number.
In short, I need to write the files:
Output1.txt, Output2.txt, Output3.txt ...
With text along the lines of:
"Output1.txt: This is file 1."
"Output2.txt: This is file 2."
"Output3.txt: This is file 3."
etc.
My code so far is below. I don't know how to insert the incrementing integer "i" into the filename so clearly all I get from this is the file "Output.txt" with the text "Output10.txt: This is file 10."
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
usingnamespace std;
int main() {
int i=0;
while (i++ <10) {
ofstream file("Output.txt");
if (file.is_open()) {
file << "Output" << i << ".txt: This is file" << i << ".\n ";
file.close();
} else { cout << "File won't open"; }
}
return 0;
}
I'm kinda curious to, I don't think it particularly matters in this case, although mixing unary and assignment operators is a big no no as results are undefined.
the for loop just looks prettier and is typically used in incrementing loops, whereas while is mostly sentinel.
1 2 3 4 5 6 7 8 9 10 11 12 13
int main() {
for (int i=0; i<10; i++) {
std::stringstream ss;
ss<<"Output"<<i<<".txt";
ofstream file(ss.str().c_str());
if (file.is_open()) {
file << "Output" << i << ".txt: This is file" << i << ".\n ";
file.close();
} else { cout << "File won't open"; }
}
return 0;
}