c ++ ofstream(someVariable)初始化

Ber*_*een 1 c++

所以我试着这样做:

#include <iostream>//For cout/cin
#include <fstream> //For ifstream/ofstream

using namespace std;

int main()
{
    string types[] = {"Creativity", "Action", "Service"};
    for(int i = 0; i < sizeof(types)/sizeof(string); i++) {
        string type = types[i];
        string filename = type + ".html";
        ofstream newFile(filename);
        //newFile << toHTML(getActivities(type));
        newFile.close();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

而且我遇到了错误.我是C++的新手,所以我不知道该尝试什么,或者如果这是可能的(SURELY它是......).我试过以下,但它实际上只是在黑暗中刺伤并没有帮助:

#include <iostream>//For cout/cin
#include <fstream> //For ifstream/ofstream

using namespace std;

int main()
{
    string types[] = {"Creativity", "Action", "Service"};
    for(int i = 0; i < sizeof(types)/sizeof(string); i++) {
        string type = types[i];
        //Attempting to add const..
        const string filename = type + ".html";
        ofstream newFile(filename);
        //newFile << toHTML(getActivities(type));
        newFile.close();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的意思是,如果我做了'ofstream newFile("somefile.html"),它会很高兴;

Die*_*ühl 6

原始IOstream库没有构造函数std::string.支持的唯一类型是char const*.您可以char const*std::string使用中获得c_str():

std::string name("whatever");
std::ofstream out(name.c_str());
Run Code Online (Sandbox Code Playgroud)

类型的字符串文字的不类型的std::string,但它是类型的char const[n],其中n是一个字符的字符串中的数字,包括终止空字符.

在C++ 2011中,文件流类得到了改进,也可以std::string在需要字符串的地方使用.