将数据格式化输出到字符串的函数——sprintf_s

函数原型:sprintf_s(char * const _Buffer, size_t const _BufferCount, char const * const _Format, …)
其中:
const _Buffer为char型数组,用来存放字符串,也就是缓存区域;
const _BufferCount为缓冲区长度,它的大小不能超过定义的const _Buffer的长度;
const _Format为格式化字符串,这里的形式和用法与printf函数是一致的。
eg:

void test()
{
	SYSTEMTIME nowtime;
	GetLocalTime(&nowtime);
	
	char m_fileName[200];
	strcpy_s(m_fileName, "BIT");
	
	sprintf_s(&m_fileName[strlen(m_fileName)], 200- strlen(m_fileName), "_%04d%02d%02d%02d%02d%02d.log", nowtime.wYear, nowtime.wMonth, nowtime.wDay, nowtime.wHour, nowtime.wMinute, nowtime.wSecond);
	cout << m_fileName << endl;
	
	fstream m_file;
	m_file.open(m_fileName, ios::out | ios::app);
	
	GetLocalTime(&nowtime);
	sprintf_s(m_fileName, 200, "%02d:%02d:%02d.%03d  Log closed.", nowtime.wHour, nowtime.wMinute, nowtime.wSecond, nowtime.wMilliseconds);
	
	m_file << m_fileName << endl << endl;
	m_file.close();
}

注意:const _Buffer最好定义为数组形式,这样可以很明确的知道其大小,不要用指针形式,以免产生不必要的问题。

猜你喜欢

转载自blog.csdn.net/weixin_44941350/article/details/123552004