1

所以我试着这样做:

#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;
}

我遇到了错误。我是 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];
        //Attempting to add const..
        const string filename = type + ".html";
        ofstream newFile(filename);
        //newFile << toHTML(getActivities(type));
        newFile.close();
    }
    return 0;
}

我的意思是,如果我执行 `ofstream newFile("somefile.html");

4

1 回答 1

6

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

std::string name("whatever");
std::ofstream out(name.c_str());

字符串文字的类型不是类型std::string,而是类型char const[n],其中n是字符串中的字符数,包括终止的空字符。

在 C++ 2011 中,文件流类得到了改进,也std::string可用于预期字符串的位置。

于 2012-10-02T18:37:19.053 回答