View Single Post
pichlo's Avatar
Posts: 6,445 | Thanked: 20,981 times | Joined on Sep 2012 @ UK
#14
Originally Posted by stlpaul View Post
And be sure it can handle the number 0 (which still takes 1 character to print on-screen). It is an easy one to miss when you're focusing on testing bigger numbers.

Using standard library functions, depending on what you know about the input number type, a perhaps easier mathematical approach could be to use log10(i)+1 but it's still up to you to handle negatives, floats, etc.
I like seeing the two above paragraphs together. Just how much is log10(0), pray tell?

Taking the "convert it to a string and count the characters" approach, in C++11, my everyday choice would be to simply do: to_string(i).length()
I'm glad someone has suggested this approach. By far the simplest, plus tried and tested using standard library rather than cooking your own and risk introducing mistakes or forgetting special cases (think numbers like -0.42).