long tmp = 1;
int size_of_tmp_long_variable would be 1
long tmp = 12;
int size_of_tmp_long_variable would be 2
long tmp = 123;
int size_of_tmp_long_variable would be 3
The size of a long always remains the same as long as you compile it the same way. You can use the sizeof operator to get the size of a datatype (or variable).
Oh, you meant like the number of characters? Sorry, misunderstood you. Like above.
#include <iostream>
#include <cmath>
#include <sstream>
int digit_count(longint number)
{
if (number == 0) return 1;
int count = 0;
while( number != 0)
{
number /= 10;
++count;
}
return count;
}
int digit_count_Wolfgang(longint number)
{
return (number == 0)? 1: (int) log10((double)abs(number)) +1;;
}
int digit_count_coder777(longint number)
{
std::stringstream stream;
stream << abs(number);
return stream.str().size();
}
int main ()
{
long a_number = -123456789;
int number_of_digits = digit_count(a_number);
int number_of_digits2 = digit_count_Wolfgang(a_number);
int number_of_digits3 = digit_count_coder777(a_number);
std::cout << "The number of digits in " << a_number << " is " << number_of_digits << std::endl;
std::cout << "The number of digits in " << a_number << " is " << number_of_digits2 << std::endl;
std::cout << "The number of digits in " << a_number << " is " << number_of_digits3 << std::endl;
return 0;
}
Here's my completely inappropriate for the beginner forum answer, using the Boost Conversion library: size_t size_of_tmp_long_variable = boost::lexical_cast<std::string>(abs(tmp)).size();
A lexical_cast is a conversion from numeric to string representation or vice versa.
1 2 3
boost::lexical_cast<std::string> // Convert the next parameter (see next line) to a string.
(abs(tmp)) // The absolute value of the tmp numeric variable (same that everyone else is doing).
.size() // Return the size of the string. (The string itself is discarded.)
It is doing essentially what Grey Wolf's digit_count_coder777() function does but using a lexical_cast instead of a stringstream.