请原谅我的天真,我只是第一次学习 C。基本上我有一系列包含格式为“HH:MM:SS”的时间戳的字符串。我正在编写一个 int tsconvert(char *) 形式的函数,它可以将时间戳转换为整数。这是我到目前为止编写的一些代码
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';
}
当我尝试使用此代码时,我收到了段错误。我的编程课上有人建议我简单地从时间戳中提取数字并将其放入一个新字符串中,但我不知道该怎么做。
最佳答案
要从时间戳 (HH:MM:SS) 中提取数字,只需使用 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);
关于转换字符串时间戳 HH :MM:SS to an integer in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22315065/