bool isValidId(int* id)
{
if(log10(*id) != 6)
{
return false;
}
return true;
}
printf("Enter ID: ");
gets(input);
c.id = atoi(input);
validID= isValidId(c.id);
if(!validID)
{
printf("Invalid ID format -(Use example 123456 format). \n");
}
This is how it looks now.I ask the user to enter an ID and check it if is valid with the isValidId method but my program is crashing when I enter an ID. Please help! Thanks
return *id >= 100000 && *id < 1000000;
I think this may be a good solution, both easy to read and efficient.
There is no need to acquire its length if you just want to judge if it is a valid id
Program crashes because the parameter of isValidId is pointer to int, not int, so
validID = isValidId(c.id);
should be
validID = isValidId(&c.id);
First of all, I don't see any reason to pass a pointer to isValidId function. You can pass an integer and calculate the number of digits.
bool isValidId(int id) {
// count digits here
}
Now there are at least two ways to calculate the number of digits. First one is to use log10. The number of digits in a 10-base integer n is (int)(log10(n) + 1). You will need to import math.h to use log10. You may check whether n <= 0 before calling log10.
The second way is to loop through n.
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With