c++ - 创建 .txt 文件时固定位数

标签 c++

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

Name_nodeNum_frequency.txt

nodeNum 为 int,频率为 float。

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

如果nodeNum是8 --> 008

如果频率为 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);

我很乐意获得一些指导。

谢谢!

最佳答案

您似乎在这里混合了 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

关于c++ - 创建 .txt 文件时固定位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25590419/

相关文章:

c++ - 使用 AMD APP SDK 2.9 创建兼容 OpenCL 1.1 的应用程序?

c++ - 在 C++ 中如何解决这些名称冲突?

c++ - 提升多种可能性的变体

c++ - 指针 vector

c++ - Pow() 真的需要 cmath header 还是 iostream 包含 cmath?

c++ - 编译 C++ 代码时出现链接器错误

c++ - 如何为模板类指定 "all parameterized types"或 "all argument lists"?

c++ - 从多个线程调用 C 文件中的函数

c++ - 在 C++ 中捕获段错误或任何其他错误/异常/信号,就像在 Java 中捕获异常一样

c++ - 如何将 constexpr 函数的参数标记为未使用?