mirror of https://github.com/mkerrisk/man-pages
Added an example program.
This commit is contained in:
parent
fefe023ea5
commit
56aee8683e
|
@ -130,6 +130,83 @@ or to
|
|||
conforms to SVID 3, 4.3BSD, ISO 9899 (C99) and POSIX, and
|
||||
.BR strtoll ()
|
||||
to ISO 9899 (C99) and POSIX 1003.1-2001.
|
||||
.SH EXAMPLE
|
||||
The program shown below demonstrates the use of
|
||||
.BR strtol ().
|
||||
The first command line argument specifies a string from which
|
||||
.BR strtol ()
|
||||
should parse a number.
|
||||
The second (optional) argument specifies the base to be used for
|
||||
the conversion.
|
||||
Some examples of the results produced by this program are the following:
|
||||
.in +0.25i
|
||||
.nf
|
||||
|
||||
$ ./a.out 123
|
||||
strtol() returned 123
|
||||
$ ./a.out ' 123'
|
||||
strtol() returned 123
|
||||
$ ./a.out 123abc
|
||||
strtol() returned 123
|
||||
Further characters after number: abc
|
||||
$ ./a.out 123abc 55
|
||||
strtol: Invalid argument
|
||||
$ ./a.out ''
|
||||
No digits were found
|
||||
$ ./a.out 4000000000
|
||||
strtol: Numerical result out of range
|
||||
|
||||
.fi
|
||||
.in -0.25i
|
||||
The source code of the program is as follows:
|
||||
.nf
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
|
||||
int
|
||||
main(int argc, char *argv[])
|
||||
{
|
||||
int base;
|
||||
char *endptr, *str;
|
||||
long val;
|
||||
|
||||
if (argc < 2) {
|
||||
fprintf(stderr, "Usage: %s str [base]\\n", argv[0]);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
str = argv[1];
|
||||
base = (argc > 2) ? atoi(argv[2]) : 10;
|
||||
|
||||
errno = 0; /* To distinguish success/failure after call */
|
||||
val = strtol(str, &endptr, base);
|
||||
|
||||
/* Check for various possible errors */
|
||||
|
||||
if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
|
||||
|| (errno != 0 && val == 0)) {
|
||||
perror("strtol");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (endptr == str) {
|
||||
fprintf(stderr, "No digits were found\\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
/* If we got here, strtol() sucessfully parsed a number */
|
||||
|
||||
printf("strtol() returned %ld\\n", val);
|
||||
|
||||
if (*endptr != '\\0') /* Not necessarily an error... */
|
||||
printf("Further characters after number: %s\\n", endptr);
|
||||
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
.fi
|
||||
.SH "SEE ALSO"
|
||||
.BR atof (3),
|
||||
.BR atoi (3),
|
||||
|
|
Loading…
Reference in New Issue