将文件名保存到特定文件夹中

时间:2014-02-10 09:09:37

标签: c++ ofstream

#include <fstream>
#include <iostream>
using namespace std;


int main(){


int value=0;

for (int i=0;i<4;i++)
{
    ofstream myfile("Etc/filename");
    string filename ="key" + i +".txt";
    myfile<<value<<endl;

}
myfile.close();
}

如何将文件保存在etc文件夹下,该文件夹有key1.txt,key2.txt,key3.txt,key4.txt? 似乎我对ofstream myfile有问题......

任何人都可以启发我怎样才能改变它?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要将正确形成的字符串作为参数传递给构造函数。例如,

std::ofstream myfile("key" + std::to_string(i) + ".txt"); 

#include <sstream> // for std::ostringstream

std::ostringstream strm;
strm << "key" << i << ".txt";
std::ofstream myfile(strm.str());

以上假设您有一个支持C ++ 11的编译器。如果你不这样做,第二个例子的一个小变化就可以了:

std::ofstream myfile(strm.str().c_str());
                                ^^^^^^^
相关问题