'Validate integer length for serial number
I had been given homework for making an app library, and I am stuck with validation. How do I validate integer length? For example, I am inputting the book serial number but the length serial number must be between 13-15 digit. I know how to do it with string, but I dont know how to do it with integer/number.
Below is the validation for the book name
if(strlen(name)>=3 && strlen(name)<=25 && validasiName(name)){
break;
}else{
system("cls");
}
and this one for the serial number
if(ISBN>=13 && ISBN<=16){
break;
}else{
system("cls");
}
Solution 1:[1]
When you're asking for the number of digits, you are really asking "how many times can I divide this number by 10 before it's less than 10?"
A simple recursive implementation would look something like this:
#include <stdio.h>
#include <limits.h>
int numLen(unsigned long num){
if(num < 10)
return 1;
return 1 + numLen(num/10);
}
int main()
{
printf("%d\n", numLen(1));
printf("%d\n", numLen(12));
printf("%d\n", numLen(ULONG_MAX));
}
Just make sure you're not putting in negative numbers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
