Hi everyone.
Im new in C++, actually im doing my first project, and i have a few questions, if you guys could help me it would be awesome. :)

In a method i have to create a .txt file, It have a parameter indicating the number of the file. But the parameter is an int variable and i need to change it to char* and then concatenate it to more char* variables.

void Labyrinth::createFile(int numberFile){
    char* numFile = (char*)numberFile;  
    char* namePt1 = "Labyrinth";
    char* namePt2 = ".txt";
    const char* finalName = HERE I NEED TO CONCATENATE namePt1+numFile+namePt2

    ofstream fileLabyrinth;

I know the file.open() needs a const char* var.
So, I dont know how to change the int var to char*, and then concatenating it to two or more char*.


6 Years
Discussion Span
Last Post by DSalas91

There are several ways to solve that problem. IMHO this is the simplest.
sprintf() is your friend here

char filename[255]; // final file name
 char* namePt1 = "Labyrinth";
int num = 5;
sprintf(filename,"%s%d.txt", namePt1,num);

ofstream fileLabyrinth(filename);

Alternate method is pure c++

string filename;
string namePt1 = "Labyrinth";
int num = 5;
filename = namePt1;
stringstream str;
str << num;
filename += str.str();
filename += ".txt";

ofstream fileLabyrinth(filename.c_str());

Edited by Ancient Dragon: n/a

Votes + Comments
He help me very well! :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.