I have a string containing a value of time in HH:MM:SS(':' are a part of the string.) format.I have to convert the time into seconds and give that value to an integer variable.I am not aware of any function that can help me do it.
Asked
Active
Viewed 90 times
0
-
2check this link http://stackoverflow.com/questions/4137748/c-converting-a-time-string-to-seconds-from-the-epoch and http://www.cplusplus.com/reference/ctime/strftime/ – Charles Stevens Jan 09 '14 at 08:33
-
http://stackoverflow.com/questions/11213326/how-to-convert-a-string-variable-containing-time-to-time-t-type-in-c This answers your question – Nazar554 Jan 09 '14 at 08:34
3 Answers
1
Use sscanf_s. For example:
void ScanTime(char* strTime)
{
int hours;
int minutes;
int seconds;
sscanf_s(strTime, "%d:%d:%d", &hours, &minutes, &seconds);
printf("hours: %d\nminutes:%d\nseconds:%d\n", hours, minutes, seconds);
}
int _tmain(int argc, _TCHAR* argv[])
{
ScanTime("13:57:44");
return 0;
}

Uri Y
- 840
- 5
- 13
-
It's correct, but the real question was how to get the total seconds... – Cees Meijer Jan 10 '14 at 21:42
-
0
Use strtol. for example::
int a=(int)strtol(numeric_string.c_str(),(char **)NULL,10);
if your intension isto simply convert HH:MM:SS, you need to write a function algorithm would be like(assuming 24Hr format):
split
the string using ":"- Convert each part using
strtol
to integer. last part+(60* middle part)+(60*60*firstpart)
will give you the actual value

Vijay
- 65,327
- 90
- 227
- 319
0
Since this is not a standard C++ function it greatly depends on what framework or library you are using.
This how it's done in Borland C++ Builder:
String Time;
Time = "12:34:56";
TDateTime DT;
try{
DT = StrToTime(Time);
}catch(...){String M = "Error converting time string: "+Time; Application->MessageBox(M.c_str(),"ERROR",MB_OK );}

Cees Meijer
- 742
- 2
- 8
- 23