You need to convert i
to a string in order to concatenate it using operator+
, otherwise you will inadvertently execute pointer arithmetic:
// C++11
#include <fstream>
#include <string> // to use std::string, std::to_string() and "+" operator acting on strings
int co = 3;
for (int i = 1; i <= co; i++)
{
ofstream file;
file.open (std::to_string(i) + ".txt");
file.close();
}
If you do not have access to C++11 (or if you want to avoid explicitly "converting i
and then concatenating"), you can use std::ostringstream
:
// C++03
#include <fstream>
#include <sstream>
std::ostringstream oss;
int co = 3;
for (int i = 1; i <= co; i++)
{
ofstream file;
oss << i << ".txt"; // `i` is automatically converted
file.open (oss.str());
oss.str(""); // clear `oss`
file.close();
}
Note: clang++ catches this mistake with the -Wstring-plus-int
warning flag (wandbox example).