zuihaobushi 2020-04-08
C++对一些常见的类型转换有库函数可用,对一些不是很常见的数据类型就没有类型转换的库函数可用了,很多时候转换起来非常麻烦。这里用C++的输入输出流的方法来做数据类型转换(这种方法本质上其实是把数据输出到缓存中然后再去读取,这个流的缓存数据是没有类型的,所以就能把xx类型的数据赋值给yy类型),实现数据类型的转换。
例子1:无符号int类型转化为十六进制 string类型
void unsigned_to_hex(unsigned int value, string& hex_string)
{
stringstream buffer;
buffer.setf(ios::showbase);
buffer <<hex << value;
buffer >> hex_stringr;
}例子2:时间类型转换为字符串类型
void time_to_string(time_t nowTime, string& nowTimeStr)
{
stringstream buffer;
buffer.setf(ios::showbase);
buffer << nowTime;
buffer >> nowTimeStr;
}实际运用:把时间戳转换为string类型
#include<iostream>
#include<ctime>
#include<sstream>
using namespace std;
void time_to_string(time_t nowTime, string& nowTimeStr)
{
stringstream buffer;
buffer.setf(ios::showbase);
buffer << nowTime;
buffer >> nowTimeStr;
}
int main()
{
time_t nowTime = time(NULL);
string nowTimeStr;
time_to_string(nowTime,nowTimeStr);
cout<<nowTimeStr<<endl;
}