在c ++中枚举文件名

时间:2012-03-08 22:26:10

标签: 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();
}

似乎是自然的实现。不幸的是,整数i被错误地连接到字符串;此外,ofstream接受char *(不是字符串)作为文件参数。 以下

#include <fstream>
#include <sstream>
string toString(int& i) {
    std::stringstream ss;
    ss << i;
    return ss.str();
}

for( int i=0; i<5; i++) {
    std::string fileName = "file" + toString(step) + ".dat";
    std::ofstream fout( (char*)fileName.c_str(), std::ios );
    //do stuff
    fout.close();
}

有效,但很麻烦。 (char*)fileName.c_str()似乎特别笨拙。 有没有更好的方法来完成这项任务?

2 个答案:

答案 0 :(得分:7)

可能性为boost::lexical_cast

std::ofstream fout(
    ("file" + boost::lexical_cast<std::string>(i) + ".dat").c_str(),
    std::ios );

没有理由将c_str()的返回值转换为传递给std::ofstream构造函数,因为它接受const char*,这正是c_str()返回的内容。

或者,以稍微不同的方式使用toString()功能:

std::ofstream fout(
    ("file" + toString(step) + ".dat").c_str(),
    std::ios );

答案 1 :(得分:0)

字符串连接不进行格式化,因此您必须单独执行此操作。在现代C ++中,您有to_string,而fstream对象将字符串作为构造函数参数:

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

在旧版本的C ++中,您可以使用stringstreams for boost = lexical_cast将整数格式化为字符串,然后使用c_str()成员函数从字符串中获取char指针:

std::string filename; // populate somehow
std::ifstream infile(filename.c_str());
相关问题