CLion recommends to use 'strtol' instead of 'scanf'

前端 未结 1 1943
暗喜
暗喜 2021-01-12 07:09
#include 

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

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

    printf(\"%d\\n\         


        
相关标签:
1条回答
  • 2021-01-12 07:51

    How do I modify this code?

    #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);
    }
    

    If successful, strtol() returns the converted long int value.

    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.

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

    Error Codes:

    EINVAL The value of base is not supported.

    ERANGE The conversion caused an overflow. Source : IBM

    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
    

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

    0 讨论(0)
提交回复
热议问题