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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:09:03  来源:igfitidea点击:

inserting int variable in file name

c++

提问by Mithil Parekh

Possible Duplicate:
Easiest way to convert int to string in C++

可能的重复:
在 C++ 中将 int 转换为字符串的最简单方法

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);