c - strtol 不改变 errno

标签 c errno strtol

我正在开发一个程序,该程序根据给定的表示时间格式 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() 显然不会检测到错误,因为它没有更新errno1,所以我无法进行错误处理。我错了什么?

最佳答案

当无法执行转换时,

strtol 不需要生成错误代码。相反,您应该使用第二个参数来存储转换后的最终位置并将其与初始位置进行比较。

顺便说一句,您的代码中还有许多其他错误,这些错误不会影响您所看到的问题,但也应该修复这些错误,例如 strncpy 使用不正确。

关于c - strtol 不改变 errno,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35260219/

相关文章:

c - 如何将 C 字符串中的计数器变量赋予函数

c++ - SetConsoleMode() 和 ENABLE_VIRTUAL_TERMINAL_PROCESSING?

c++ - 在 C++ 中使用 strtol 获取 long double

c - 为什么 strtol 需要指向指针的指针而不是单个指针?

c - 左值需要作为一元 '&"操作数

c - 当您在基于开关的函数中转换空指针时,有什么方法可以避免重复代码?

C++:sqlite3 是否使用 errno 代码?

c - VxWorks PPC 中 errno 始终返回零

mysql - SQL无法创建表,errno 150

c - 为什么 strtol() 对于非常大的数字返回 -1?