打开文件,文件名为变量

Pat*_*ryk 2 c++ string variables file-io

我想创建名称由...组成的文件int variables + ".txt".我已经尝试过了:

std::string filename = i + ".txt";

sprintf这不是最好的方法 - 至少在我看来,因为它需要一个C带有分配内存的样式字符串

sprintf( tmp, "%d.txt", i);
std::string filename = tmp;
Run Code Online (Sandbox Code Playgroud)

也许itoa是最好的选择?

Joe*_*Joe 5

您可以使用字符串流

#include <sstream>

...
    std::stringstream ss;
    ss << i << ".txt";

    std::string filename = ss.str();
Run Code Online (Sandbox Code Playgroud)