strtol将使用错误号 [英] strtol using errno

查看:150
本文介绍了strtol将使用错误号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

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

void main(void)
{
     int data;
     char * tmp;
     data = strtol("23ef23",&tmp,10);
     printf("%d",errno);
     getchar();
}

输出为0 ...

output is 0 ...

为什么?

我使用Visual Studio 2010的C ++
code必须是C89兼容。

i am using visual studio 2010 C++ code must be C89 compatible.

推荐答案

与strtol 仅设置错误号溢出条件,不以指示解析故障。为了这个目的,你必须检查结束指针的值,但是你需要存储一个指向原始字符串:

strtol only sets errno for overflow conditions, not to indicate parsing failures. For that purpose, you have to check the value of the end pointer, but you need to store a pointer to the original string:

char const * const str = "blah";
char const * endptr;

int n = strtol(str, &endptr, 0);

if (endptr == str) { /* no conversion was performed */ }

else if (*endptr == '\0') { /* the entire string was converted */ }

else { /* the unconverted rest of the string starts at endptr */ }

我觉得唯一必需的误差值是下溢和溢出。

I think the only required error values are for underflow and overflow.

相反,如果整个字符串已经在转换被消耗,你有 * endptr ='\\ 0',这可能是你可能要检查的额外的东西

Conversely, if the entire string has been consumed in the conversion, you have *endptr = '\0', which may be an additional thing you might want to check.

这篇关于strtol将使用错误号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆