Lê Phương Nam Lê Phương Nam - 15 days ago 5
C++ Question

Passing const char * to file.open(), strange behavior

I'm having problem with the code below. I'm experiencing different behaviors depending on what IDE I'm using.

Dev-C++: Runs fine. However, if I pass

GenerateFileName(0,0)
to
file.open()
, no file is created.

Visual Studio 2013: Runs fine in all cases, however, the name of the file generated looks like

ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌPùD


or something like that, and the file itself has no extension (I expect a
.txt
file ).

int main()
{
ofstream file;
file.open(GenerateFileName(3, 0));
file << 1 << endl;
file.close();
_getch();
}

const char* GenerateFileName(int Instance_nth, int Input_nth)
{
string filename = to_string(Instance_nth);
filename += "_";
filename += to_string(Input_nth);
filename += ".txt";

return filename.c_str();
}

Answer
const char* GenerateFileName(int Instance_nth, int Input_nth)
{
    string filename = to_string(Instance_nth);
    filename += "_";
    filename += to_string(Input_nth);
    filename += ".txt";

    return filename.c_str();
}

You're returning a pointer to the data internally stored by filename while it is destroyed with GenerateFileName's ending: the returned value is a dangling pointer, and your code is undefined behaviour.

What you can do is returning a std::string instead of const char*:

std::string GenerateFileName(int Instance_nth, int Input_nth)
{
    string filename = to_string(Instance_nth);
    filename += "_";
    filename += to_string(Input_nth);
    filename += ".txt";

    return filename;
}

Usage would become:

file.open(GenerateFileName(3, 0).c_str());