How can I find out how many digits are in an integer in C++?

0
16
Asked By CurlyPineapple32 On

I'm trying to develop a C++ program that takes an integer input between 0 and 9999 and outputs the number of digits in that integer. I initially tried using the `.size()` function, but it doesn't work with integers, only strings. I was wondering if type casting could help, but I'm not sure I'm doing it right. Here's my code, but it's not functioning as expected:

```
#include
using namespace std;

int main() {
int inputNum;
int numDigits;
cin >> inputNum;
// test print
cout << "number: " << inputNum << endl;
// test print
cout << "digits: " << static_cast(numDigits) << numDigits.size() << endl;
return 0;
}
```

5 Answers

Answered By LogicFinder88 On

One simple way to find the number of digits is to keep dividing the number by 10 until it reaches zero. Each division effectively reduces the number of digits by one. Here’s a quick approach: ```
while(inputNum > 0) {
inputNum /= 10;
numDigits++;
}``` Just ensure to initialize `numDigits` to 0 before the loop starts.

Answered By HelpfulCoder77 On

Instead of trying to cast an integer to a string, you can use `std::to_string(inputNum).size()` to get the number of digits directly. Just include `` at the top of your file. Note that your `numDigits` variable is uninitialized, so be careful with that. You need to assign the value from `to_string` to a variable for it to work.

Answered By CodeExplorer44 On

Thanks for the help, everyone! I tried dividing by 10, but it gave me a new problem. I might post again about that issue if I can't figure it out!

Answered By NumberCruncher101 On

You could also consider using logarithms for this task. If you take the logarithm base 10 of the number, you can easily determine the count of digits by rounding down and adding 1: `numDigits = floor(log10(inputNum)) + 1;` Just remember, this won’t work for 0, so make sure to handle that case separately.

Answered By NewbieProgrammer92 On

If you're feeling adventurous, you could check the number size using a series of `if` statements like:
```
if (inputNum < 10) numDigits = 1;
else if (inputNum < 100) numDigits = 2;
else if (inputNum < 1000) numDigits = 3;
else numDigits = 4;
``` This way is a bit more manual but it could be fun to implement!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.