gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:38:37 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com