strtol表现不尽如人意,c

Joh*_*n_C 0 c string int strtol

#include<limits.h>
#include<errno.h>

long output;

errno = 0;
output = strtol(input,NULL,10);
printf("long max = %ld\n",LONG_MAX);
printf("input = %s\n",input);
printf("output = %ld\n",output);
printf("direct call = %ld\n",strtol(input,NULL,10));
if(errno || output >= INT_MAX || output <= INT_MIN) {
    printf("Input was out of range of int, INT_MIN = %d, INT_MAX = %d\n",INT_MIN,INT_MAX);
    printf("Please input an integer within the allowed range:\n");
}
Run Code Online (Sandbox Code Playgroud)

当上面的代码输入{'1','2','3','4','5','6','7','8','9','0的输入数组时", '1'}

我得到的输出:

long max = 9223372036854775807
input = 12345678901
output = -539222987
direct call = 3755744309
Run Code Online (Sandbox Code Playgroud)

发生了什么... strtol似乎正在遭受溢出但没有设置errno

Mat*_*Mat 6

您很可能不包括必需<stdio.h>和/或<stdlib.h>标头.

一旦包含以下代码,您的代码就可以正常工作(GCC在64位模式下):

$ cat t.c
#include<limits.h>
#include<errno.h>
#include<stdlib.h>
#include<stdio.h>

int main (void)
{
    long output;
    char input[] = "12345678901";
    errno = 0;
    output = strtol(input,NULL,10);
    printf("long max = %ld\n",LONG_MAX);
    printf("input = %s\n",input);
    printf("output = %ld\n",output);
    printf("direct call = %ld\n",strtol(input,NULL,10));
    if(errno || output >= INT_MAX || output <= INT_MIN) {
        printf("Input was out of range of int, INT_MIN = %d, INT_MAX = %d\n",INT_MIN,INT_MAX);
        printf("Please input an integer within the allowed range:\n");
    }
    return 0;
}

$ gcc -Wall -Wextra -pedantic t.c
$ ./a.out
long max = 9223372036854775807
input = 12345678901
output = 12345678901
direct call = 12345678901
Input was out of range of int, INT_MIN = -2147483648, INT_MAX = 2147483647
Please input an integer within the allowed range:
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你应该errnostrtol通话结束后立即保存,你调用的库函数strtol和你的条件可以改变它的值.