How do I count no 0 as one digit?

Mar 28, 2011 at 9:57pm
Hi, may I know how do I count number zero as one digit?

My code for converting a series of number into a digits is like this (Bear in mind number belong to a set of {0,1,2,3,4,5,6,7,8,9}):

cin >> number;
digits = floor( log10( abs( number ) ) ) + 1;

if (number == 0)
{ digits = 1; }

When I input the number as 0123456789, it does not detect 0 as one digit. Basically it ignore number zero. May I know where do I do wrong?

Thanks in advance.
Mar 28, 2011 at 10:33pm
if you want to count the leading 0 too, you must read it in as a string.
that is because, when you enter 0123 it will actualy be 123, as you correctly noticed.
Just like we do.. or do you write 123 as 0123 when doing calculations on paper? ;)
Last edited on Mar 28, 2011 at 10:35pm
Mar 28, 2011 at 10:37pm
Hmm... actually I am not doing it for the calculation part. I just want to save the number into a text file :)

But is there no other way or formula so that we can still count number zero as one digit without reading the number as a string?
Mar 28, 2011 at 10:48pm
You can read it as a string and convert it to a number when you need to. However, you gotta realize that integers are values, not rows of digits. 0123 and 123 have the same value, and it's the value that's being saved to an integer.
Mar 28, 2011 at 10:48pm
no, i meant it in general. i dont know anybody who wirtes an 0 in front of numbers when doing calculations anywhere.

but back to your question, that is why cin will not give you an int/long int/whatever with a leading 0. it will just ignore it.
so no, there is no other way. because cin ignores the leading 0, there is no way you can find out if the input was 123, 0123, 00000000123 and so on when dealing with numerical types.
only strings, char arrays and such things will help you.

but whats wrong with using strings? a simple .size(); and you have the number of digits. ok maybe you have to check if any thing of the input is no number.
but entering something like "1abc" in your code above will result to number = 1.
so make it a little search, eventualy extract a substring and size and you are done.
Mar 29, 2011 at 9:27pm
Right.. I am using string now. And it work by using the ctype.h in order to differentiate between number and a letter. Thanks for the idea.
Mar 29, 2011 at 9:44pm
Although cin ignores leading zeros, be aware that literals with a leading zero are in octal.
Topic archived. No new replies allowed.