Count number of digits in a given integer

To count the number of digits in a number we have to divide that number by 10 until it becomes 0 or less than 0. If you divide any number by 10 and store the result in an integer then it strips the last digit. So we have to apply the same logic here also.

Logic

After taking the input from the user, run one while loop that runs until the user given number becomes 0. Inside the loop for each iteration increase the counter variable by one and divide the user given number by 10 and store it in the same variable again.

Notice here we are using /= operator that performs division and stores the result in the same variable again.

Once the loop is over we have to print counter variable “count” containing the total number of digits.

Program

#include <iostream>

using namespace std;

int main() {

    int num, temp;
    int count = 0;

    // Take input from user
    cout << "Enter any number : ";
    cin >> num;

    // Store to temporary variable.
    temp = num;
    
    while(temp != 0) {

        // Increment counter
        count++;

        // Remove last digit of 'temp'
        temp /= 10;
    }

    cout << endl << "Total digits in " << num << " : "  << count;

    return 0;
}

Output

Enter any number : 123456
Total digits in 123456 : 6