【问题标题】:strtol not working as expected [closed]strtol 没有按预期工作[关闭]
【发布时间】:2018-03-29 11:23:52
【问题描述】:

我无法使用 strtol 将字符串转换为长字符串。在字符串中的数字之前有一个前导 "." 返回 0。 没有"." strtol 会按预期返回3456。

#include <stdio.h>                                                              
#include <stdlib.h>   

int main ()
{                                                                   
    char str[20] = " . 3456\r\n";                                                                    

    long ret = strtol(str, NULL, 10);                                            
    printf("ret is %ld\n",ret);

    return(0);                                                                   
}

【问题讨论】:

  • 你为什么希望strtol 跳过前导点?
  • 用例是什么?你想要一个值为 3456 的 long 还是一个值为 0.3456 的 double?
  • @KarstenKoop 长与 3456。. 不是十进制值,它只是传感器返回的字符,所以我想忽略它。
  • @homeGrown 你想用减号做什么?
  • @zwol 它不报告负值。我只问过忽略.

标签: c string strtol


【解决方案1】:

strto* 库函数只会跳过前导空格。如果要跳过其他文本,则需要手动完成。 ctype.h 中的 isxxx 函数可以帮助解决这个问题:

#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char **argv)
{
    char *p, *endp;
    unsigned long ret;
    int fail = 1;

    if (argc != 2) {
        fprintf(stderr, "usage: %s number-to-parse\n", argv[0]);
        return 2;
    }
    p = argv[1];
    while (*p && !isdigit(*p)) p++;

    errno = 0;
    ret = strtoul(p, &endp, 10);     
    if (endp == p)
        printf("'%s': no number found\n", str);
    else if (*endp && !isspace(*endp))
        printf("'%s': junk on line after number\n", str);
    else if (errno)
        printf("'%s': %s\n", str, strerror(errno));
    else {
        printf("'%s': parsed as %lu\n", str, ret);
        fail = 0;
    }
    return fail;
}

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多