我正在开发一个程序,该程序根据给定的表示时间格式 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
,所以我无法进行错误处理。我错了什么?
最佳答案
当无法执行转换时,
strtol
不需要生成错误代码。相反,您应该使用第二个参数来存储转换后的最终位置并将其与初始位置进行比较。
顺便说一句,您的代码中还有许多其他错误,这些错误不会影响您所看到的问题,但也应该修复这些错误,例如 strncpy
使用不正确。
关于c - strtol 不改变 errno,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260219/