...
Instead of these functions, try inputing the value as a string and then converting it to an integer valoue using strtol()
or a related function INT00-A.
Non-Compliant Example
...
This non-compliant code example converts the string stored in the static array buff
to a signed integer value using the atoi()
function.
Code Block |
---|
char buff [25];
int int_var;
fgets(buff, sizeof buff, stdin);
int_var = atoi(buff);
|
The atoi()
, atol()
, and atoll()
functions convert the initial portion of astring pointed to int
, long int
, and long long int
representation, respectively. Except for the behavior on error, they are equivalent to
Code Block |
---|
atoi: (int)strtol(nptr, (char **)NULL, 10)
atol: strtol(nptr, (char **)NULL, 10)
atoll: strtoll(nptr, (char **)NULL, 10)
|
Unfortunately, atoi()
and related functions lack a mechanism for reporting errors for invalid values. Specifically, the atoi()
, atol()
, and atoll()
functions:
...
uses the scanf()
function to read a string from stdin
and covert it to an integer value. The scanf()
and fscanf()
functions have undefined behavior if the value of the result of this operation cannot be represented
...
Non-Compliant Example 2
This non-compliant example uses the sscanf()
function to convert a string to as an integer. The sscanf()
function has the same problems as atoi()
.
Code Block |
---|
char buff [25]; int int_varsi; fgets(buff, sizeof buff, stdin); sscanfscanf("%d", buff, &int_var&si); |
Compliant Solution
The following compliant example uses strtol()
to input an integer value and provides error checking to make sure that the value is a valid integer in the range of int
.
...