Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to count the number of digits in an integer with C++

2 Answers

0 votes
#include <iostream>
#include <string>

int countDigitsString(int value) {
    // Convert the number to a string
    std::string text = std::to_string(value);

    // If negative, ignore the leading '-'
    if (!text.empty() && text[0] == '-') {
        return static_cast<int>(text.size()) - 1;
    }

    return static_cast<int>(text.size());
}

int main() {
    int number = -12345;

    int digits = countDigitsString(number);

    std::cout << "Number: " << number << "\n";
    std::cout << "Digit count (String method): " << digits << "\n";
}



/*
run:

Number: -12345
Digit count (String method): 5

*/

 



answered May 15, 2021 by avibootz
edited 6 hours ago by avibootz
0 votes
#include <iostream>
#include <cmath>

int countDigitsLog10(int value) {
    int num = std::abs(value);

    // Zero must be handled explicitly
    if (num == 0) {
        return 1;
    }

    // Use floor(log10(n)) + 1
    return static_cast<int>(std::floor(std::log10(num))) + 1;
}

int main() {
    int number = 987654321;

    int digits = countDigitsLog10(number);

    std::cout << "Number: " << number << "\n";
    std::cout << "Digit count (log10 method): " << digits << "\n";
}



/*
run:

Number: 987654321
Digit count (log10 method): 9

*/

 



answered Jul 23, 2021 by avibootz
edited 6 hours ago by avibootz
...