[英]How to convert string time to unsigned int in c++
I need to convert string
time to unsigned int
i test my program with atoi/strtoul/atol
and string stream
but they don't work correctly what am i missing??? 我需要将
string
时间转换为unsigned int
我用atoi/strtoul/atol
和string stream
测试我的程序,但它们无法正常工作,我缺少什么?
string CurrentTime(){
time_t rawtime;
struct tm * timeinfo;
char bffr [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (bffr,80,"%T",timeinfo);
// puts (bffr);
return bffr;
}
int main(){
string new_time;
new_time = CurrentTime();
stringstream strValue;
strValue << new_time;
unsigned int stime;
strValue >> stime;
cout<<stime<<endl;
cout<<new_time<<endl;
}
and 和
int main(){
string new_time;
new_time = CurrentTime();
unsigned int stime =atoi(new_time.c_str());
cout<<stime<<endl;
cout<<new_time<<endl;
but both of them print stime
:just only hour for example 10
但是他们两个都打印
stime
:仅一个小时,例如10
and print new_time
: for example 10:20:15
并打印
new_time
:例如10:20:15
Your string stream is not working because of a delimiter ":". 由于定界符“:”,您的字符串流不起作用。 you need to get around it.
您需要解决它。 Try the following code:
尝试以下代码:
string new_time;
new_time = CurrentTime();
std::string finalstring;
std::string delim = ":";
size_t pos = 0;
while ((pos = new_time.find(delim)) != std::string::npos)
{
finalstring += new_time.substr(0, pos);
new_time.erase(0, pos + delim.length());
}
stringstream strValue;
strValue << finalstring;
strValue << new_time;
unsigned int stime;
strValue >> stime;
cout << stime << endl;
It seems that %T doesn't work well with strftime
function call. 看来%T在
strftime
函数调用中不能很好地工作。
But there is a workaround for this. 但是有一个解决方法。
%T
is actually %H:%M:%S
%T
实际上是%H:%M:%S
Thus, 从而,
strftime (bffr, 80, "%H:%M:%S", timeinfo);
strftime(bffr,80,“%H:%M:%S”,timeinfo);
should work fine for your code. 应该适合您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.