I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:
int x;
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
count++;
x = x/10;
}
From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.
Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?
To count number of digits divide the given number by 10 till number is greater than 0. For each iteration increment the value of some count variable. Step by step descriptive logic to count number of digits in given integer using loop.
Now, we will see how to count the number of digits without using a loop. We can also count the number of digits with the help of the logarithmic function. The number of digits can be calculated by using log10(num)+1, where log10() is the predefined function in math.
isDigit(s. charAt(i)) will count the number of digits in the given string. 'Character. isDigit' will count the number of each digit in the string.
In your particular example you could read the number as a string and count the number of characters.
But for the general case, you can do it your way or you can use a base-10 logarithm.
Here is the logarithm example:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double n;
cout << "Enter a number: ";
cin >> n;
cout << "Log 10 is " << log10(n) << endl;
cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
return 0;
}
int count = (x == 0) ? 1 : (int)(std::log10(std::abs((double)(x)))))) + 1;
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