我需要创建具有特定文件名格式的文件(在 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/