To extract the numbers from the timestamp (HH:MM:SS), just use sscanf():
const char *str = "01:02:03";
int h, m, s;
sscanf(str, "%d:%d:%d", &h, &m, &s);
printf ("%d, %d, %d\n", h, m, s);
Frage
Forgive me for my naivety I'm just learning C for the first time. Basically I have a series of strings that contain a timestamp in the format "HH:MM:SS". I'm looking to write a function of the form int tsconvert(char *) that can covert the timestamp to an integer. Here is some code I've written so far
int tsconvert(char *timestamp)
{
int x;
removeColon(timestamp,8);
x = atoi(timestamp);
return x;
}
void removeColon(char *str1, int len)
{
int j = 0;
for (int i = 0; i < len; i++)
{
if (str1[i] == ':')
{
continue;
}
else
{
str1[j] = str1[i];
j++;
}
}
str1[j] = '\0';
}
When I try and use this code however I get a segmentation error. Some one in my programing class suggested that I simply extract the numbers from the timestamp and place those in a new string but I'm not sure how to do that.
Lösung
To extract the numbers from the timestamp (HH:MM:SS), just use sscanf():
const char *str = "01:02:03";
int h, m, s;
sscanf(str, "%d:%d:%d", &h, &m, &s);
printf ("%d, %d, %d\n", h, m, s);
Andere Tipps
My suggestion is not much different than @Younggun Kim but with recommended additional error checking.
Use "%n"
to determine if scanning completed to the end of the string with no additional junk.
// -1 error else 0 - 86399
long tsconvert(const char *timestam) {
unsigned h, m, s;
int n = 0;
int cnt = sscanf(timestam, "%2u:%2u:%2u %n", &h, &m, &s, &n);
if (cnt != 3 || timestam[n] != '\0') return -1 ; // Format Error;
if (h >= 24 || m >= 60 || s >= 60) return -1; // Range Error
// 0 - 86400-1
return ((h*60 + m)*60L + s;
}