c ++将time_t转换为字符串并再次返回 [英] c++ convert time_t to string and back again
问题描述
我想将 time_t 转换为字符串并再次返回.
我想使用 ctime() 将时间转换为字符串.
我似乎在 google 或 time.h 头文件上找不到任何东西,有什么想法吗?
基本上我想做的是将日期存储在文件中,然后将其读回,以便我可以再次将其用作 time_t.
此外,没有 std、mfc 之外的库引用.
还要注意的是,这必须在 Windows xp 及更高版本上运行,仅此而已.
I want to convert a time_t to a string and back again.
I'd like to convert the time to a string using ctime().
I can't seem to find anything on google or the time.h header file, any ideas?
Basically what I'm trying to do is store a date in a file, and then read it back so I can use it as a time_t again.
Also, no library references outside of std,mfc.
One more note, this will have to function on Windows xp and above and that's it.
我想要做的就是将 time_t 转换为字符串(我不在乎它是否是人类可读的),然后将其转换回 time_t.我基本上只是试图将 time_t 存储到一个文件中并再次读取它(但我不想要任何代码,因为除了 time_t 之外,文件中还会有更多信息).
All I want to do is convert a time_t into a string(I don't care if it's human readable) and then convert it back to a time_t. I'm basically just trying to store the time_t into a file and read it again(but I don't want any code for that, as there will be more info in the file besides a time_t).
推荐答案
您必须编写自己的函数才能做到这一点.这些函数将任何原始类型(或任何重载 operator<<和/或 operator>> 的类型)转换为字符串,反之亦然:
You'll have to write your own function to do that. These functions convert any primitive type (or any type which overloads operator<< and/or operator>>) to a string, and viceversa:
template<typename T>
std::string StringUtils::toString(const T &t) {
std::ostringstream oss;
oss << t;
return oss.str();
}
template<typename T>
T StringUtils::fromString( const std::string& s ) {
std::istringstream stream( s );
T t;
stream >> t;
return t;
}
这篇关于c ++将time_t转换为字符串并再次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!