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