Use strtol() or a related function to convert a string token to an integer. The strtol(), strtoll(), strtoul(), and strtoull() functions convert the initial portion of a string token to long int, long long int, unsigned long int, and unsigned long long int representation, respectively. These functions provide more robust error handling than alternative solutions.
...
Non-Compliant Code Example
This non-compliant code example converts the string token stored in the static array buff to a signed integer value using the atoi() function.
| Code Block | ||
|---|---|---|
| ||
int si;
if (argc > 1) {
si = atoi(argv[1]);
}
|
The atoi(), atol(), and atoll() functions convert the initial portion of a string token 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:
- do not need to set
errnoon an error - have undefined behavior if the value of the result cannot be represented
Non-Compliant Example
This non-compliant example uses the sscanf() function to convert a string token to an integer. The sscanf() function has the same problems as atoi().
| Code Block | ||
|---|---|---|
| ||
int si;
if (argc > 1) {
sscanf(argv[1], "%d", &si);
}
|
...
| Include Page | ||||
|---|---|---|---|---|
|
...