简体   繁体   English

解析时间军事时间字符串的特殊情况

[英]corner case of parsing a time military time string

usually, most military times are like this 通常,大多数军事时期都是这样

12:34:56

I already figured an method to extract the Hours,mins and secs into their own strings. 我已经找到了一种将Hours,mins和secs提取到自己的字符串中的方法。

However, there is a corner case that i can't seem to figure out 但是,有一个极端的情况,我似乎无法弄清楚

example: 例:

12::

after extracting the number and converting to integers, result is 0. That is good. 提取数字并将其转换为整数后,结果为0。这很好。 However, i need two 0's to properly represent the time 但是,我需要两个0才能正确表示时间

char *hh = argv[2];
char *mm, *ss;
char *array[3];
char *temp =strchr(argv[2],':');
mm = temp + 1;

/*if(*mm == ':'){

  *mm = "00";
}*/

*temp = '\0';
temp = strchr(mm, ':');
ss = temp+1;
*temp = '\0';

if you look at the commented if part, that is my attempt to check if the next pointed value is a semicolon. 如果您查看注释的if部分,那是我尝试检查下一个指向的值是否为分号。 If it is, all i need to do is it with two 0's. 如果是的话,我要做的就是加上两个0。

Any clue how to deal with this? 有什么线索如何处理吗?

It would be much better to extract this data as integers, not strings. 将这些数据提取为整数而不是字符串会更好。

Something like: 就像是:

bool parse_hms(int *hours, int *minutes, int *seconds, const char *hms)
{
  *hours = *minutes = *seconds = 0;

  return sscanf(hms, "%d:%d:%d", hours, minutes, seconds) > 0;
}

should work. 应该管用。 Note that the function assumes that all three pointers are valid. 请注意,该函数假定所有三个指针均有效。 It returns true if at least one of the numbers was parsed out. 如果至少解析出一个数字,则返回true Non-parsed numbers will be set to 0 (which of course is also valid as an element value). 未解析的数字将设置为0(当然,它也可以作为元素值使用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM