相关疑难解决方法(0)

正确使用strtol

下面的程序将字符串转换为long,但根据我的理解,它也会返回错误.我依赖的事实是,如果strtol将字符串成功转换为long,那么第二个参数strtol应该等于NULL.当我用55运行以下应用程序时,我收到以下消息.

./convertToLong 55
Could not convert 55 to long and leftover string is: 55 as long is 55
Run Code Online (Sandbox Code Playgroud)

如何成功检测strtol的错误?在我的应用程序中,零是有效值.

码:

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

static long parseLong(const char * str);

int main(int argc, char ** argv)
{
    printf("%s as long is %ld\n", argv[1], parseLong(argv[1]));
    return 0;
 }

static long parseLong(const char * str)
{
    long _val = 0;
    char * temp;

    _val = strtol(str, &temp, 0);

    if(temp != '\0')
            printf("Could not convert %s to long and …
Run Code Online (Sandbox Code Playgroud)

c c++

26
推荐指数
3
解决办法
3万
查看次数

标签 统计

c ×1

c++ ×1