1.获取时间要用到的头文件
#include<time.h>
#include<string>
2.使用写入文件需要使用的头文件
#include<fstream>
3.获取当前系统时间到string变量filename(随便起的)中,因为char类型的数组变量无法使用 + 来组合你想要的名字
//代码前要声明名称空间std
time_t currentTime=time(NULL);//注意NULL大小写
char chCurrentTime[256];
strftime(chCurrentTime,sizeof(chCurrentTime),%Y%m%d %H%M%S,localtime(&chCurrentTime));
string stCurrentTime=chCurrentTime;
string filename="data"+stCurrentTime+".txt";
4.要写入文件需要创建一个ofstream对象
ofstream fout;
5.然后需要将这个对象与文件关联起来,使用open()函数,文件即之前我们将时间戳整合得到的filename
使用open函数打开文件时,如果没有该文件则默认创建一个此名称的文件,如果已有该文件则默认覆盖之前内容,具体可以查阅相关资料
fout.open(filename.c_str());//文件名后面一定要加这个.c_str() 该函数返回一个指针常量,因为貌似open()函数没法直接加string的变量,返回的字符串与string内容相同
6.之后就是往该文件里面写入内容,使用方法与cout相同
fout<<"test"<<endl;
7.最后将文件关闭即可
fout<<flush;//确保文件在无操作时关闭 可以省略
fout.close();
最后写了一个简单的小例子
#include <fstream>
#include<iostream>
#include<time.h>
#include<string>
int main()
{
using namespace std;
time_t currentTime=time(NULL);
char chCurrentTime[256];
strftime(chCurrentTime,sizeof(chCurrentTime),"%Y%m%d %H%M%S",localtime(¤tTime));
string stCurrentTime=chCurrentTime;
string filename="data"+stCurrentTime+".txt";
ofstream fout;
fout.open(filename.c_str());
int v_set,v_act,a_set,a_act;
int i=0;
while(i<5)
{
cin>>v_set>>v_act>>a_set>>a_act;
fout<<v_set<<", "<<v_act<<", "<<a_set<<", "<<a_act<<", "<<endl;
i++;
}
fout<<flush;
fout.close();
}
运行之后会在程序目录下得到一个txt文件,效果如下