I need to read a positive number only (unsigned long long
), a nothing is more, so I use scanf("%llu", &num);
. But it also allows to input negative values.
How to validate positive numbers in this case? The user must input a positive number in [0..2^(64)-1] but he can miss and input a negative value in same interval. But I can't declare a long long
variable to check it cuz it can contain 2^64 - 1 totally.
You could read the input into a character array using fgets()
, check if the first character is a character other than a digit and then use -
ve symbolstrtoull()
to convert it to unsigned long long
.
char c, buff[100];
fgets(buff, sizeof(buff), stdin);
//sscanf(buff, "%*[ ]%c", &c);
sscanf(buff, "%s", buff);
//if( (c<'0' || c>'9') )
if(buff[0]<'0' || buff[0]>'9')
{
printf("\nNegative or invalid number!");
}
else
{
num=strtoull(buff, NULL, 10);
}
strtoull()
will return ULLONG_MAX
(defined in limits.h
) and sets errno
to ERANGE
(to use these, errno.h
header file must be included) if the value returned by it won't fit in an unsigned long long
.
if(num==ULLONG_MAX && errno==ERANGE)
{
printf("\nOverflow");
}
The %*[ ]
in the sscanf()
is used to ignore the leading white spaces in the string.
The first non-space character is found and stored in c
whose value is checked.
As explained here, sscanf(buff, "%s", buff);
would trim the string buff
on both sides to get rid of the spaces.