本文介绍了CLion建议使用"strtol"代替"scanf"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

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

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

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

    return 0;
}

scanf(%d",& num);

Clang-Tidy:"scanf"用于将字符串转换为整数值,但函数不会报告转换错误;考虑改用"strtol"

我用CLion写了一个非常简单的代码,建议我用"strtol"代替"scanf".

I wrote a very simple code with CLion and it recommends me 'strtol' instead of 'scanf'.

但是我只使用整数变量,没有字符串.我不知道为什么会弹出检查消息.

But I'm using only integer variable and there is no strings. I can't figure out why the inspection message pops up.

如何修改此代码?

推荐答案

#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()返回 0 执行.如果正确的值超出可表示的范围值,根据符号, strtol()返回 LONG_MAX LONG_MIN 价值.如果不支持base的值,请 strtol()返回 0 .

If unsuccessful, strtol() returns 0 if no conversion could be performed. If the correct value is outside the range of representable values, strtol() returns LONG_MAX or LONG_MIN, according to the sign of the value. If the value of base is not supported, strtol() returns 0.

如果 strtol()不成功,则将errno设置为以下值之一:

If unsuccessful strtol() sets errno to one of the following values:

错误代码:

EINVAL 不支持base的值.

EINVAL The value of base is not supported.

ERANGE (转换)导致转换溢出.来源: IBM

ERANGE The conversion caused an overflow. Source : IBM

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

Can you check overflow using scanf() for example?

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 在他的评论中(在其他主题中)说像错误一样处理警告.


Maybe off-topic but, Jonathan Leffler says in his comments(in another topics) that handle warnings just as errors.

这篇关于CLion建议使用"strtol"代替"scanf"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 00:10