Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the number of digits of an integer

Tags:

c

  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

like image 281
user1930901 Avatar asked Dec 04 '25 17:12

user1930901


2 Answers

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);
like image 130
Fei Jiang Avatar answered Dec 06 '25 06:12

Fei Jiang


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;
}
like image 45
taskinoor Avatar answered Dec 06 '25 06:12

taskinoor