所以我尝试这样做:
#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"); 一切都会很开心
最佳答案
原始的 IOstream 库没有采用 std::string
的构造函数。唯一支持的类型是 char const*
。您可以使用 c_str()
从 std::string
获取 char const*
:
std::string name("whatever");
std::ofstream out(name.c_str());
字符串文字的类型不是 std::string
类型,而是 char const[n]
类型,其中 n
是字符串中的字符数,包括终止空字符。
在 C++ 2011 中,文件流类得到改进,在需要字符串的地方也采用 std::string
。
关于c++ ofstream(someVariable) 初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12696078/