...
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 1
This non-compliant code example converts the string stored in the static array buff
to a signed integer value using the atoi()
function.
...
- do not need to set errno on an error
- have undefined behavior if the value of the result cannot be represented
Non-Compliant Example 2
This non-compliant example uses the sscanf()
function to convert a string to an integer. The sscanf()
function has the same problems as atoi()
.
Code Block |
---|
char buff [25]; int int_var; fgets(buff, sizeof buff, stdin); sscanf("%d", buff, &int_var); |
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
.
...
If you are attempting to convert a string to a smaller interger type (int
, short
, or signed char
), then you only need test the result against the limits for that type. The tests do nothing if the smaller type happens to have the same size and representation on a particular compiler.
References
- Jack Klein. Bullet Proof Integer Input Using strtol(). http://home.att.net/~jackklein/c/code/strtol.html
- ISO/IEC 9899-1999 Section 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions; Section 7.20.1.2 The atoi, atol, and atoll functions; 7.19.6.7 The sscanf function