CLion建议使用“strtol”而不是“scanf”

rbl8hiat  于 2023-03-17  发布在  其他
关注(0)|答案(1)|浏览(162)
#include <stdio.h>

int main(int argc, char** argv) {
    int num = 0;

    printf("Input: ");
    scanf("%d", &num); <<<

    printf("%d\n", num);

    return 0;
}

扫描(“%d”,&编号);

  • 铿锵整齐:“scanf”用于将字符串转换为整数值,但函数不会报告转换错误;考虑使用“strtol”代替 *

我用CLion写了一个非常简单的代码,它建议我使用“strtol”而不是“scanf”。
但是我只使用整型变量,没有字符串,我不明白为什么会弹出检查消息。
如何修改此代码?

6tdlim6h

6tdlim6h1#

如何修改此代码?

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

enum { INPUT_SIZE = 30 };

int main () {
    char *ptr;
    long ret;
    char str[INPUT_SIZE];

    fgets(str, INPUT_SIZE, stdin);    
    ret = strtol(str, &ptr, 10);

    if( ret == LONG_MAX || ret == LONG_MIN ) {
        perror("!! Problem is -> ");
    }
    else if (ret) {
        printf("The number is %ld\n", ret);
    }
    else {
        printf("No number found input is -> %s\n", ptr);
    }

    return(0);
}

如果成功,strtol()返回转换后的long int值。
如果不成功,则strtol()在无法执行转换的情况下返回0。如果正确的值在可表示值的范围之外,则strtol()根据值的符号返回LONG_MAXLONG_MIN。如果不支持base的值,则strtol()返回0
如果不成功,strtol()将errno设置为以下值之一:

  • 错误代码:*
    EINVAL不支持base的值。
    ERANGE转换导致溢出。源:IBM

例如,您可以使用scanf()检查溢出吗?

Input:  1234 stackoverflow
Output: The number is 1234

Input:  123nowhitespace
Output: The number is 123

Input:  number is 123
Output: No number found input is -> number is 123

Input:  between123between
Output: No number found input is -> between23between

Input:  9999999999999999999
Output: !! Problem is -> : Result too large

也许离题了,但是Jonathan Leffler在他的评论(在另一个主题中)中说,* 把警告当作错误来处理。*

相关问题