char[12] filename;
FILE * file;
for(i=0;i<IMAX;i++){
snprintf(filename,12,"file%2d.txt",i);
file=fopen(filename, "w");
/* Do stuff with file ... */
}
#include <iostream>#include <sstream>#include <fstream>#include <string>int main(void){ unsigned num; std::cin >> num; for (unsigned i = 1; i <= num; i++) { std::stringstream ss; ss << "file" << i << ".txt"; std::string filename; ss >> filename; std::ofstream file(filename.c_str()); } return 0;}
Of course, this is really not something you want to be doing in C++. Using a more expressive language lets you do this in many fewer lines of code. For example, here's the exact same program in Haskell:main = mapM_ (flip writeFile "" . Text.Printf.printf "file%d.txt") . enumFromTo 1 . read =<< getLine
Read up on control flow.
posted by qxntpqbbbqxl at 8:11 AM on November 4, 2008