C++ 将文件名保存到特定文件夹中 #包括 #包括 使用名称空间std; int main(){ int值=0; 对于(int i=0;i

C++ 将文件名保存到特定文件夹中 #包括 #包括 使用名称空间std; int main(){ int值=0; 对于(int i=0;i,c++,ofstream,C++,Ofstream,,您需要将格式正确的字符串作为参数传递给构造函数 #include <fstream> #include <iostream> using namespace std; int main(){ int value=0; for (int i=0;i<4;i++) { ofstream myfile("Etc/filename"); string filename ="key" + i +".txt"; myfile<<v

,您需要将格式正确的字符串作为参数传递给构造函数

#include <fstream>
#include <iostream>
using namespace std;


int main(){


int value=0;

for (int i=0;i<4;i++)
{
    ofstream myfile("Etc/filename");
    string filename ="key" + i +".txt";
    myfile<<value<<endl;

}
myfile.close();
}


string filename
从未被使用过…@parrowdice这似乎是流myfile(“folder/”+filename)的一个问题;这是C++11。但即使在C++11中,我想我也会为此使用
std::ostringstream
这似乎更自然。或者我只会使用一条语句:
std::ofstream myfile(“key”+std::to_string(I)+.txt”)
。但通常,您需要一些额外的格式,至少在数字变大时是这样;这意味着
std::ostringstream
(我已经做了很多次了,但我总是需要使用
std::setw
并将填充字符设置为
'0'
,以确保文件名排序正确。)@JamesKanze我同意。我正在添加stringstream版本。我也将缩短C++11版本。
std::ofstream myfile("key" + std::to_string(i) + ".txt"); 
#include <sstream> // for std::ostringstream

std::ostringstream strm;
strm << "key" << i << ".txt";
std::ofstream myfile(strm.str());
std::ofstream myfile(strm.str().c_str());
                                ^^^^^^^