创建.txt文件的固定数字位数

时间:2014-08-31 08:54:16

标签: c++

我需要创建具有特定文件名格式的文件(在Windows上)。格式为:

Name_nodeNum_frequency.txt

nodeNum为int,频率为float。

这两个变量应该用固定数字写成:

if nodeNum is 8 --> 008

if frequency is 4.88421 --> 4.884

这是功能:

create_file(int nodeNum, double frequency)
{
  char buffer [50];

  //convert int to string
  itoa(nodeNum, buffer, 10);
  string sNodeNum = string(buffer);

  //not sure about the double
  //tried to_string but I got:
  // more than instance of overloaded function matches the argument list


  string fileName = ("Name_" + sNodeNum + "_" + sfreq + "MHZ");
  FILE* pFile = OpenFile(fileName);
}

我尝试使用%d,但似乎我不应该这样做:

string fileName = ("Delay_" + "%3d" + "_" + sfreq + "MHZ" , sNodeNum);

我很乐意提供一些指导。

谢谢!

2 个答案:

答案 0 :(得分:3)

你好像在这里混合使用C和C ++。在C中执行此操作的简单方法是:

#include <stdio.h>

int main()
{
  int sNodeNum = 8;
  double sfreq = 4.88421;
  char filename[50];
  sprintf(filename, "Delay_%03d_%.3fMHZ.txt", sNodeNum, sfreq);
  FILE* pFile = fopen(filename, "w");
  return 0;
}

另一方面,如果你想使用C ++,你应该做一些改变:

#include <iomanip>
#include <fstream>
#include <sstream>
#include <iostream>

int main()
{
  int sNodeNum = 8;
  double sfreq = 4.88421;    
  std::ostringstream ss;
  ss << "Delay_" << std::setfill('0') << std::setw(3) << sNodeNum
     << "_" << std::setprecision(4) << sfreq << "MHZ.txt";
  std::string filename(ss.str());    
  std::ofstream fout(filename.c_str());
  return 0;
}

这两种方法中的每一种都会打开一个文件进行写作,名称为Delay_008_4.884MHZ.txt

答案 1 :(得分:1)

Live demo link

#include <string>
#include <iomanip>
#include <iostream>

int nodeNum = 8;
float frequency = 4.88421f;

std::ostream& out = std::cout; // put your std::ofstream file or std::ostringstream

std::ios::fmtflags flags = out.flags();

out.width(3);
out.fill('0'); 
out.setf(std::ios::right, std::ios::adjustfield);
out << nodeNum << std::endl;

flags = out.flags(flags);

out.precision(3);
out.setf(std::ios::fixed, std::ios::floatfield); 
out << frequency;

out.flags(flags);

甚至更简单:

out << std::setw(3) << std::setfill('0') << std::right << nodeNum << std::endl;

out << std::setprecision(3) << std::fixed << frequency;

输出:

008
4.884