【发布时间】:2017-04-08 20:22:07
【问题描述】:
下面的代码有问题。根据我使用的 IDE,我会遇到不同的行为。
Dev-C++: 运行良好。但是,如果我将GenerateFileName(0,0) 传递给file.open(),则不会创建任何文件。
Visual Studio 2013:在所有情况下都运行良好,但是生成的文件的名称看起来像
ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌPùD
或类似的东西,文件本身没有扩展名(我希望是 .txt 文件)。
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();
}
【问题讨论】:
-
在
GenerateFileName()中,变量filename在函数返回时被销毁,所以函数的返回值是垃圾。 -
您正在返回一个指向局部变量的指针。那是UB。
-
只需从函数中返回字符串
-
将
GenerateFileName的返回类型改为std::string -
在 C++11 中
ofstream::opencan handlestd::string以及const char *。