dtbsezxw28056 2016-10-15 15:31
浏览 86
已采纳

函数,以字符串和数字作为创建文件名的参数

I have to create different data files in a loop. There are three file-types i want to generate like

typeA%00d.txt,

typeB%00d.txt and

typeC%00d.txt

For this i want to implement a function that takes a sequential number and a string as parameters.

Something similar to this:

void make_file(paarvec data, int count){ 

 int size = data.size();
 char filename[160];
 sprintf(filename, "name%03d.txt", count);

 ofstream out_data(filename);
 for(int n=0; n<size; ++n){
    out_data << data[n].first << "\t" << data[n].second << endl;
    }
 out_data.close();
}

But is there a way that i also can change the "name" of the file with an argument. So that i can write:

std::string timestring = "timedata";
std::string timestring = "pathdata";
...

for(int i=0; i<N; ++i){
  ...
  make_file(time_data, timestring ,count);
  make_file(frac_data, fracstring ,count);
  make_file(path_data, pathstring ,count);
}  
  • 写回答

1条回答 默认 最新

  • douzong5835 2016-10-15 15:38
    关注

    Just change your function to:

    void make_file(paarvec data, const std::string &name, int count){ 
    
      int size = data.size();
      char filename[160];
      snprintf(filename, sizeof(filename), "%s%03d.txt", name.c_str(), count);
      ...
    

    Note I changed sprintf to snprintf - it is a good habit to prevent bad surprises in your code like buffer overflow.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64