Reputation: 101
I want to know how to get the length of a long long
. I have a simple function where I am trying to get the length of a long long
and I also get an error.
while (numberArray[i].length() > MAX_INPUT)
{
cout << "ERROR: Program can only take in a number length " << MAX_INPUT << " or less. Try again ->";
cin >> numberArray[i];
}
NOTE: numberArray
is a static that was made an int
. The call to .length()
worked perfectly but I wanted to change the type to long long
and now .length()
does not seem to work anymore.
This is the type of message I get from the compiler every time I try and run the code:
In function 'void takeNumbers(std::__cxx11::string&, long long int (&)[11], int)': main.cpp:48:26: error: request for member 'length' in 'numberArray[i]', which is of non-class type 'long long int' while (numberArray[i].length() > MAX_INPUT){
Upvotes: 2
Views: 2340
Reputation: 7482
Just for completeness, another approach could be using a sort of lookup table as the following:
unsigned num_digits(long long x)
{
x = std::abs(x);
if(x < 10)
return 1;
else if(x < 100)
return 2;
else if(x < 1000)
return 3;
//keep going ....
}
Upvotes: 0
Reputation: 234705
You'll need to roll your own function: the length of a number is arbitrary in that it assumes a radix, and assumptions need to be made about the treatment of non positive numbers. As a starting point, consider
unsigned length(unsigned long long n, unsigned radix = 10)
{
unsigned l;
for (l = 0; n; n /= radix, ++l);
return l;
}
where you can extend this for negative numbers (should they increase the length by one?) to suit personal taste.
Note that this will 0
for the number 0
: that's how I think of the length of 0
, but that's not to everyone's taste.
Upvotes: 2
Reputation: 11789
In C++, plain old data types such as long long int
do not have member functions for obtaining their length. If you want the length of an integer, you can convert the number to a string, and then take it's length. For example:
while (std::to_string(numberArray[i]).length() > MAX_INPUT)
This makes use of the std::to_string
function which is used for converting non-string POD types to the std::string
class.
But suppose you needed to handle negative integers as well. The above wouldn't work since the leading minus sign would be counted as part of the length (Unless you want that). Another approach would be to use a loop along with division to find the length of an integer and place this loop in a function, as follows:
std::size_t numDigits(long long int n)
{
std::size_t length = 0;
do
{
++length;
n /= 10;
} while (n);
return length;
}
Then in your loop:
while (numDigits(numberArray[i]) > MAX_INPUT)
Depending on your goal, you may pick either approach.
Upvotes: 3