M
migurus
I see that atof and strtod both recognize "INF", or "+INF", or "-INF"
as special case and return accordingly infinite value. But atoi and
strtol do not know about this special case - why? Is there a trick to
it?
example to demonstrate this feature:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
main(int argc, char *argv[])
{
long lx;
double dx;
char buf[20], *p = NULL;
strcpy(buf, argc == 2 ? argv[1] : "+INF");
lx = atol(buf); printf("lx=%li\n", lx);
dx = atof(buf); printf("dx=%f\n", dx);
lx = strtol(buf, &p, 10);
printf("lx=%li, p=%s, errno=%i\n", lx, p, errno);
dx = strtod(buf, &p);
printf("dx=%f, p=%s, errno=%i\n", dx, p, errno);
exit(0);
}
Please see results below
Compiled under SCO OSR5 (tried both native SCO compiler and gcc)
../c '+INF'
lx=0
dx=inf
lx=0, p=INF, errno=22
dx=inf, p=, errno=22
../c '-INF'
lx=0
dx=-inf
lx=0, p=-INF, errno=22
dx=-inf, p=, errno=22
Very similar behavoir under linux and gcc (errno works differently
somehow):
../c '+INF'
lx=0
dx=inf
lx=0, p=+INF, errno=0
dx=inf, p=, errno=0
../c '-INF'
lx=0
dx=-inf
lx=0, p=-INF, errno=0
dx=-inf, p=, errno=0
Any thoughts whether this is a problem with atoi/strtol? I expected
them behave similarly to atof/strtod, maybe my expectations are
unwarranted?
as special case and return accordingly infinite value. But atoi and
strtol do not know about this special case - why? Is there a trick to
it?
example to demonstrate this feature:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
main(int argc, char *argv[])
{
long lx;
double dx;
char buf[20], *p = NULL;
strcpy(buf, argc == 2 ? argv[1] : "+INF");
lx = atol(buf); printf("lx=%li\n", lx);
dx = atof(buf); printf("dx=%f\n", dx);
lx = strtol(buf, &p, 10);
printf("lx=%li, p=%s, errno=%i\n", lx, p, errno);
dx = strtod(buf, &p);
printf("dx=%f, p=%s, errno=%i\n", dx, p, errno);
exit(0);
}
Please see results below
Compiled under SCO OSR5 (tried both native SCO compiler and gcc)
../c '+INF'
lx=0
dx=inf
lx=0, p=INF, errno=22
dx=inf, p=, errno=22
../c '-INF'
lx=0
dx=-inf
lx=0, p=-INF, errno=22
dx=-inf, p=, errno=22
Very similar behavoir under linux and gcc (errno works differently
somehow):
../c '+INF'
lx=0
dx=inf
lx=0, p=+INF, errno=0
dx=inf, p=, errno=0
../c '-INF'
lx=0
dx=-inf
lx=0, p=-INF, errno=0
dx=-inf, p=, errno=0
Any thoughts whether this is a problem with atoi/strtol? I expected
them behave similarly to atof/strtod, maybe my expectations are
unwarranted?