Best way to write function to count digits?

This code finds the first,last and # of digits of an integer. Problem is using an if statement to find the # of digits only works up to nine digits. suggestions on a better way to do this?

#include <iostream>
#include <string>
using namespace std;

int first_digit (int n)
{
    const int base = 10;
    int x;
    do
          {
          x = n % 10;
          }
      while (n /= base);
      return x;
}

int last_digit (int n)
{
    int x;
    {x = n % 10;}
    return x;
}

int digits (int n)
{
    n = abs(n);
    if (n < 10) return 1;
    else if (n < 100) return 2;
    else if (n < 1000) return 3;
    else if (n < 10000) return 4;
    else if (n < 100000) return 5;
    else if (n < 1000000) return 6;
    else if (n < 10000000) return 7;
    else if (n < 100000000) return 8;
    else if (n < 1000000000) return 9;
    else 
    return 10;
}

int main()
{int input;
cout << "Please enter a number: ";
cin >> input;
cout << "The first digit is ";
cout << first_digit (input) << endl;
cout << "The last digit is ";
cout << last_digit (input) << endl;
cout << input << " has " << digits (input) << " digit(s)." << endl;
system ("pause");
return 0;
}
1
2
3
4
5
6
7
8
9
int digits( int n )
{
    n = abs(n);

    int i = 0;
    do { i++; } while ( n /= 10 );

    return ( i );
}
Works fine up until about twelve digits?
And what is the problem? By the way are you sure that objects of type int can have 12 digits on your system?
At twelve digits you get close and/or reach the max size of an int (232 on a 32 bit system, 264 on a 64 bit system). Use long long int or other larger data types for bigger numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <limits>

int main()
{
    std::cout << "The maximum number of decimal digits an int can hold on this system is "
        << std::numeric_limits<int>::digits10 << '\n' ;

    int input;
    cout << "Please enter a number: ";
    cin >> input;
    cout << "The first digit is ";
    cout << first_digit (input) << endl;
    cout << "The last digit is ";
    cout << last_digit (input) << endl;
    cout << input << " has " << digits (input) << " digit(s)." << endl;
    system ("pause");
    return 0;
}
Last edited on
That's the limitation of an integer on your system. Use long long and gain up to 19 digits.
@ vlad
I'm running 64 bit I wasn't aware that made a difference and I was hoping to find a way to do it so It could find numbers past 12?

@ modshop
ah thanks this should help
Topic archived. No new replies allowed.