strtol的正确使用

Correct usage of strtol(strtol的正确使用)
本文介绍了strtol的正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The program below converts a string to long, but based on my understanding it also returns an error. I am relying on the fact that if strtol successfully converted string to long, then the second parameter to strtol should be equal to NULL. When I run the below application with 55, I get the following message.

./convertToLong 55
Could not convert 55 to long and leftover string is: 55 as long is 55

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

How can I successfully detect errors from strtol? In my application, zero is a valid value.

代码:

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

static long parseLong(const char * str);

int main(int argc, char ** argv)
{
    printf("%s as long is %ld
", 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 != '')
            printf("Could not convert %s to long and leftover string is: %s", str, temp);

    return _val;
}

推荐答案

大功告成.temp 本身不会为空,但是如果整个字符串被转换,它会指向一个空字符,所以你需要解引用它:

You're almost there. temp itself will not be null, but it will point to a null character if the whole string is converted, so you need to dereference it:

if (*temp != '')

这篇关于strtol的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)