C++ 在文件名中插入 int 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11437702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
inserting int variable in file name
提问by Mithil Parekh
Possible Duplicate:
Easiest way to convert int to string in C++
How can I insert int variable while creating .vtk file? I want to create file at every k step. i.e. so there should be series of files, starting from file_no_1.vtk, file_no_2.vtk, ... to file_no_49.vtk .
如何在创建 .vtk 文件时插入 int 变量?我想在每 k 步创建文件。即所以应该有一系列文件,从 file_no_1.vtk, file_no_2.vtk, ... 到 file_no_49.vtk 。
while(k<50){
ifstream myfile;
myfile.open("file_no_.vtk");
myfile.close();
k++;
}
回答by Rob?
In C++11:
在 C++11 中:
while(k<50){
ifstream myfile("file_no_" + std::to_string(k) + ".vtk");
// myfile << "data to write\n";
k++;
}
回答by Zeta
Use a stringstream
(include <sstream>
):
使用stringstream
(包括<sstream>
):
while(k < 50){
std::ostringstream fileNameStream("file_no_");
fileNameStream << k << ".vtk";
std::string fileName = fileNameStream.str();
myfile.open(fileName.c_str());
// things
myfile.close();
k++;
}
回答by wallyk
Like this:
像这样:
char fn [100];
snprintf (fn, sizeof fn, "file_no_%02d.vtk", k);
myfile.open(fn);
Or, if you don't want the leading zero (which your example shows):
或者,如果您不想要前导零(您的示例显示):
snprintf (fn, sizeof fn, "file_no_%d.vtk", k);