一个实例 c++ VS2017 读取当前系统时间 以时间来命名txt文件

  • 时间:
  • 浏览:
  • 来源:互联网

实例代码

#include <ctime>
#include <iostream>
#include <string>
#pragma warning(disable:4996)

using namespace std;

/*
编译时出现以下报错,
C4996 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
解决办法:
在头文件处,增加:#pragma warning(disable:4996)

相关的解决办法,详见以下链接
https://blog.csdn.net/weixin_40937100/article/details/88809384
*/

int main()
{
	string str_year, str_mon, str_mday, str_hour, str_min, str_sec;
	string str_now;
	string str_filename;

	time_t now = time(0);
	tm *this_monent = localtime(&now);

	//tm结构的变量都属于int
	cout << "这一刻属于哪一年=" << 1900 + this_monent->tm_year << "\n";
	cout << "这一刻属于该年哪个月=" << this_monent->tm_mon << "\n";
	cout << "这一刻属于该月哪一日=" << this_monent->tm_mday << "\n";
	cout << "这一刻属于该日哪个时辰=" << this_monent->tm_hour << "\n";
	cout << "这一刻属于该时辰哪一分钟=" << this_monent->tm_min << "\n";
	cout << "这一刻属于该分钟哪一秒钟=" << this_monent->tm_sec << "\n";

	//把int转成string
	str_year = to_string(1900 + this_monent->tm_year);
	//月,小于10前面加0
	if (this_monent->tm_mon < 10)
	{
		str_mon = "0" + to_string(this_monent->tm_mon);
	}
	else
	{
		str_mon = to_string(this_monent->tm_mon);
	}
	//日,小于10前面加0
	if (this_monent->tm_mday < 10)
	{
		str_mon = "0" + to_string(this_monent->tm_mday);
	}
	else
	{
		str_mday = to_string(this_monent->tm_mday);
	}
	//小时,小于10前面加0
	if (this_monent->tm_hour < 10)
	{
		str_mon = "0" + to_string(this_monent->tm_hour);
	}
	else
	{
		str_hour = to_string(this_monent->tm_hour);
	}
	//分钟,小于10前面加0
	if (this_monent->tm_min < 10)
	{
		str_min = "0" + to_string(this_monent->tm_min);
	}
	else
	{
		str_min = to_string(this_monent->tm_min);
	}
	//秒,小于10前面加0
	
	if (this_monent->tm_sec < 10)
	{
		str_sec = "0" + to_string(this_monent->tm_sec);
	}
	else
	{
		str_sec = to_string(this_monent->tm_sec);
	}

	//把所有string按需要组成文件名(filename),再与".txt",组成一个"filename.txt"
	str_now = str_year + str_mon + str_mday + str_hour + str_min + str_sec;
	str_filename = str_now + ".txt";
	cout << "这一刻的txt文件名=" << str_filename << "\n";
}

 

运行程序,输出结果:

 

本文链接http://xiahunao.cn/article/show-994407.html