C++ 枚举c+中的文件名+;

C++ 枚举c+中的文件名+;,c++,C++,我想生成枚举文件名的列表 file1.dat file2.dat … 下面的代码 #include<fstream> for( int i=0; i<5; i++) { std::ofstream fout( "file" + i + ".dat", std::ios ); //do stuff fout.close(); } 这很有效,但很麻烦(char*)fileName.c_str()似乎特别笨拙。 有没有更好的方法来完成这项任务?一种可能是:

我想生成枚举文件名的列表

file1.dat
file2.dat
…
下面的代码

#include<fstream>
for( int i=0; i<5; i++) {
    std::ofstream fout( "file" + i + ".dat", std::ios );
    //do stuff
    fout.close();
}
这很有效,但很麻烦
(char*)fileName.c_str()
似乎特别笨拙。 有没有更好的方法来完成这项任务?

一种可能是:


字符串连接不进行格式化,因此必须单独进行格式化。在现代C++中,你有<代码> toSyth,FStand对象将字符串作为构造函数参数:

std::ifstream infile(std::string("file") + std::to_string(i) + ".dat");

在C++的旧版本中,可以使用String String为Boox= ListalyCasic将整数格式化为字符串,然后使用<代码> CyString()/Cux>成员函数从字符串中获得char指针:

std::string filename; // populate somehow
std::ifstream infile(filename.c_str());

请参见导入?最近使用Java(或者等等,这是Objective-C吗,我从来没有使用过Objective-C)?Oops:应该是“包含”,而不是“导入”。我先学了java。谢谢:
fstream
构造函数被固定为在C++11中使用
const std::string&
文件名,因此不再需要
C_str()
。还有
ostringstream
。因此,只为一个例程添加boost依赖项未免太过分了。@SigTerm,是的,他正在使用它:只是通知OP存在
lexical\u cast
。多谢了,这正是我想要的。
std::ofstream fout(
    ("file" + toString(step) + ".dat").c_str(),
    std::ios );
std::ifstream infile(std::string("file") + std::to_string(i) + ".dat");
std::string filename; // populate somehow
std::ifstream infile(filename.c_str());