Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

clion

#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' used to convert a string to an integer value, but function will not report conversion errors; consider using 'strtol' instead


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.

How do I modify this code?

like image 684
EnDelt64 Avatar asked Jun 11 '18 09:06

EnDelt64


1 Answers

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.

like image 110
snr Avatar answered Sep 27 '22 17:09

snr