View Single Post
Posts: 1,141 | Thanked: 781 times | Joined on Dec 2009 @ Magical Unicorn Land
#12
Originally Posted by Mentalist Traceur View Post
Oh, now if you are stuck trying to figure out what the length of "[string 2]" would be, since that's an integer/float/double variable, I would approach it like this:

You know that the amount of digits in the number determines the length.

You know in decimal counting systems, each digit is one greater multiple of 10, essentially.

For an integer, then, you can figure out how many digits it will be by dividing it by ten until it becomes zero (as C++ will floor decimal results for intergers).

For every power of ten it has, you add one more to your digits counter.

With a little bit of thinking, it should be possible for you to figure out how to convert the above into code. If you can't after a while, I can show you what I've written to do so. (Hint, either a loop, or a series of if/else-if checks with less/great -than comparisons.)

With a little more thinking, you can adapt such approaches to floats/doubles as well.

There's other ways too, of course, usually involving using other fancy C++ classes and stuff, if that's the route you want to go.
You should become a teacher, you have a great way of suggesting solutions without flat-out telling the answer. This counting function sounds exactly like an exercise I did while learning programming.

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.

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()

to_string is implemented in the C++ standard library as a wrapper around snprintf which then converts the result from a c-style character array and returns a std::string. So, following with woody's suggestion, you could pretty easily implement something like that yourself even in an older compiler which lacks C++11 support. This should be able to handle any type of number you throw at it.
 

The Following User Says Thank You to stlpaul For This Useful Post: