我正在开发一个程序,该程序在给定一个 char 数组的情况下执行计算,该数组表示格式中的时间HH:MM:SS
。它必须解析各个时间单位。这是我的代码的精简版,只关注时间:
unsigned long parseTime(const char *time)
{
int base = 10; //base 10
long hours = 60; //defaults to something out of range
char localTime[BUFSIZ] //declares a local array
strncpy(localTime, time, BUFSIZ); //copies parameter array to local
errno = 0; //sets errno to 0
char *par; //pointer
par = strchr(localTime, ':'); //parses to the nearest ':'
localTime[par - localTime] = '\0'; //sets the ':' to null character
hours = strtol(localTime, &par, base); //updates hours to parsed numbers in the char array
printf("errno is: %d\n", errno); //checks errno
errno = 0; //resets errno to 0
par++; //moves pointer past the null character
}
问题是,如果输入无效(例如aa:13:13
),strtol()
显然不会检测到错误,因为它没有更新errno
到1
,所以我无法进行错误处理。我怎么了?