gpt4 book ai didi

c++ - 如何在 C++ 中将字符串时间转换为无符号整数

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:58 25 4
gpt4 key购买 nike

我需要将 string 时间转换为 unsigned int 我用 atoi/strtoul/atolstring 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;
}

 int main(){
string new_time;
new_time = CurrentTime();
unsigned int stime =atoi(new_time.c_str());
cout<<stime<<endl;
cout<<new_time<<endl;

但它们都打印 stime :just only hour for example 10

并打印new_time:例如10:20:15

最佳答案

由于分隔符“:”,您的字符串流无法正常工作。你需要绕过它。试试下面的代码:

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;

关于c++ - 如何在 C++ 中将字符串时间转换为无符号整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com