strtol使用errno

Nah*_*hum 1 c c89

我有以下代码:

#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();
}
Run Code Online (Sandbox Code Playgroud)

输出为0 ...

为什么?

我使用visual studio 2010 C++代码必须与C89兼容.

Ker*_* SB 23

strtol仅设置errno溢出条件,而不是指示解析失败.为此,您必须检查结束指针的值,但是您需要存储指向原始字符串的指针:

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 */ }
Run Code Online (Sandbox Code Playgroud)

我认为唯一需要的错误值是下溢和溢出.

相反,如果转换中已经消耗了整个字符串,那么*endptr = '\0'您可能需要检查其他内容.