将字符串时间戳HH:MM:SS转换为C中的整数

问题描述 投票:2回答:2

原谅我,我只是第一次学习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';
}

但是,当我尝试使用此代码时,出现了细分错误。我编程班的一个人建议我只是从时间戳中提取数字,然后将它们放在新的字符串中,但是我不确定该怎么做。

c string timestamp atoi
2个回答
1
投票

要从时间戳(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);

1
投票

我的建议与@Younggun Kim没什么不同,但是建议您进行其他错误检查。

使用"%n"确定扫描是否已完成到字符串末尾而没有其他垃圾。

// -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;
}
© www.soinside.com 2019 - 2024. All rights reserved.