Maria
Maria

Reputation: 1

Beginner c++ How to return the number of digits in a number?

The code below is what I've gotten so far. The goal of this portion of my assignment was to return the number of digits in a number, what am I doing wrong?

int numDigits(int num)
{
    int n, div, digits;

    cout << "Enter a number: " << endl;
    cin >> n;

    digits=1;
    while(div> 0)
    {
            digits= digits + 1;
            div= 10;
            div= div * 10;
    }

return digits;
}

Upvotes: 0

Views: 954

Answers (5)

Adam Martin
Adam Martin

Reputation: 1218

You're assigning div to 10 inside the loop every time, instead of starting it at 10. You also can just check if div is greater than the answer or not. Also, you seem to be passing in num but then accepting n from stdin. I've removed the stdin portion.

int numDigits(int num) //return the number of digits in num
{
    int div, digits;

    digits=1;
    div= 10;
    while(div > num)
    {
            digits= digits + 1;
            div= div * 10;
    }

    return digits;
}

A few other issues though:

  1. Don't use using namespace std, it can cause problems in bigger projects
  2. You don't need to use a separate accumulator, you can just keep dividing by 10.

Sample:

int numDigits(int num) //return the number of digits in num
{
    int digits = 1;
    while(num >= 10)
    {
            digits= digits + 1;
            num/=10;
    }

    return digits;
}

However, the more idiomatic C++ way would be something like

int numDigits(int num)
{
    //Note error handling needed for num==0
    return std::ceil(std::log10(std::abs(num)));
}

Upvotes: 4

Chase Kregor
Chase Kregor

Reputation: 402

int getDigit(int num, int index) // return the index'th digit 
{
    int result;
    for(int i=0; i < index; i++)
    {
        num = num / 10;
    }
    result = num % 10;
    return result;
}

Upvotes: -2

user6891026
user6891026

Reputation: 1

int numDigits(int num) {
    int DigitCount = 0;
    while(num > 0) {
        DigitCount++;
        num /= 10;
     }
     return DigitCount;
}

Upvotes: 0

Sravan
Sravan

Reputation: 141

Agree with the solutions provided by various people with division operator and increment the counter for counting the number of integers until you reach dividend being '0'.

One more way is to write the input number to a stringstream and take the string length. I would say it as hack, but a simpler one though.

Upvotes: 0

Agmr
Agmr

Reputation: 1

You have to define number of digits in num, not in keyboard input

int numDigits(int num) //return the number of digits in num
{
  int div, digits;
  div = 10;
  digits=1;
  while(num/div > 0)
  {
        digits= digits + 1;
        div= div * 10;
  }
  return digits;
}

Upvotes: 0

Related Questions