C++ fstream - 如何在 .open() 中添加变量而不是字符串?

标签 c++ string variables fstream ofstream

我正在尝试编写一个程序,该程序将在一个循环中的文件夹中创建/输出多个文件,但出现错误。这样的事情可以做吗?一直在寻找没有运气。谢谢! 这是一个例子:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream text;
    for(int i = 0; i < 100; i++);
    {
        text.open("folder/" + i + ".txt");
        text << "This is text file #" << i << "."<< endl;
        text.close();
    }
return 0;
}

最佳答案

您正在尝试添加 const char *和一个 number ,这是不可能的。这不是你想要的。相反,您应该在循环中执行以下操作

ofstream text;
for(int i = 0; i < 100; i++);
{
    string str;
    str = "folder/";

    std::stringstream ss;
    ss << i; //convert int to stringstream

    str += ss.str(); //convert stringstream to string 
    str + =  ".txt";

    text.open(str); //use final string
    text << "This is text file #" << i << "."<< endl;
    text.close();
} 

不要忘记包含 #include <sstream> .

关于C++ fstream - 如何在 .open() 中添加变量而不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32645980/

相关文章:

java - 变量类型与值类型相同吗?

c++ - 没有函数指针参数的隐式向上转换?

c++ - 使用 std::async 启动类成员函数的模板函数

c++ - 模板隐式实例化发生在使用之前

javascript - 如何检查数组中的单词是否存在于给定字符串中

linux - 如何查找和删除字符串中的多个子字符串

java - 在循环外使用字符串变量

ios - Xcode 4.6.2 : Variable Doesn't Show Up In Outlets

c++ - 从其他专门函数调用专门函数

java - Java中如何检查值的类型?