【问题标题】:How could I check whether strtol parsed anything at all?我如何检查 strtol 是否解析了任何内容?
【发布时间】:2013-06-26 08:16:57
【问题描述】:

strtol 从给定的字符串中解析出一个长整数。好的。但是我怎么能检查是否有解析过的东西呢?

例如:

  • 在以下字符串上使用strtol会产生0:
    0abcdef
  • 但是,在以下字符串上使用strtol 也会产生0
    abcdef

因此,我无法确定该函数是解析了有效的 0 还是根本没有解析任何内容并因此返回 0

我如何验证strtol 工作正确还是返回错误?有其他选择吗?

I read that strtol sets an errno 在 Unix 上,但我对 Win32 平台特别感兴趣。

【问题讨论】:

    标签: c winapi strtol


    【解决方案1】:

    这是strtol()的签名:

    long int strtol(const char *nptr, char **endptr, int base);
    

    如果endptr 不为NULL,strtol() 将第一个无效字符的地址存储在*endptr 中。 所以你可以在之后简单地比较*endptrnptr,如果不同,strtol() 已经解析了*endptr 之前的字符。

    【讨论】:

    • 不一定是第一个无效字符——例如一个初始的空格序列是有效的,但是即使字符串以空格开头,如果不进行转换,那么保证@987654329的值@ 将存储在 *endptr 中。
    【解决方案2】:

    使用 strtol 的第二个参数:它是char **。它将填充第一个无效字符:take a look at this manpage

    例子:

    #include <stdlib.h>
    int main()
    {
        char       *ptr = 0;
        const char *str = "1234abcd";
    
        printf("%d\n", strtol(str, &ptr, 10)); // -> 0
        printf("ptr: %c\n", *ptr); // -> 'a'
        while (*str && *str != *ptr)
        {
            printf("parsed: %c\n",  *str); // -> '1' '2' '3' & '4'
            ++str;
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 2011-05-22
      • 2013-12-29
      • 2012-05-16
      • 2011-03-15
      • 2010-09-17
      • 1970-01-01
      • 2011-11-26
      相关资源
      最近更新 更多