c++ ofstream(someVariable) 初始化

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

我遇到了错误。我是 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/

相关文章:

c++ - 覆盖虚拟成员函数时,为什么覆盖函数总是变为虚拟?

c++ - 如何将基类的枚举传递给子类的构造函数

c++ - 具有递归算法的 SIGSEGV

c++ - 在 C++ 中使用 ffmpeg 编码视频时如何设置 moov 原子位置

c++ - 显式释放底层 C++ iostream 的内存

php - 对于从 C++ 开始的 php 开发人员,是否有一个地方可以让我们看到 PHP <=> C++ 等效库/函数?

c++ - 在哪里可以找到不同 STL 容器复杂性(性能)的比较?

c++ - 使用 boost iostreams 过滤器(关闭且不可复制)

c++ - 创建 OpenGL 对象期间出错

c++ - 如果应用程序永无止境,auto_ptr 指向的内存会泄漏吗?