How can I remove leading zeros from an integer generated by a loop and store it as an array?
I have chains of chains for
.
For instance:
for (int i=300; i>200; i--)
{(somefunction)*i=n;
cout<<n;
}
Here's the output to the screen like this:
f=00000000000100023;
I want to store the 100023 portion of that number (I just ignore all zeros up to the beginning of the zero, but then keeping the zeros that follow) as an array.
Like this:
array[0]=1;
array[1]=0;
array[2]=0;
array[3]=0;
array[4]=2;
array[5]=3;
How can I achieve this?
a source to share
This is the answer to the question, because they are all there, I just don't think you see a solution.
First of all, if they are integers The answer to the answer along with the other answers are good, keep some of them by skipping the "store in array" part. Also, as pointed out in the comment to your question, this part is duplicate .
But with your new code, the solution I had in mind was John's solution . You just have to figure out how to ignore leading zeros, which is easy:
std::vector<int> digits;
bool inNumber = false;
for (int i=300; i>200; i--)
{
int value = (somefunction) * i;
if (value != 0)
{
inNumber = true; // its not zero, so we have entered the number
}
if (inNumber)
{
// this code cannot execute until we hit the first non-zero number
digits.push_back(value);
}
}
Basically, just don't start pushing until you reach the actual number.
a source to share
In light of the edited question, my original answer (below) is not the best. If you absolutely must have the output in an array instead of a vector, you can start with GMan's answer and then feed the resulting bytes into the array. You can do the same with JohnFx's answer as soon as you find the first non-zero digit in its results.
I am assuming it f
has a type int
, in which case it does not preserve leading zeros.
int f = 100023;
First, you need to find the required length of the array. You can do this by taking a magazine (base 10) f
. You can import the cmath library to use the function log10
.
int length = log10(f);
int array[length];
length
should now be 6.
Then you can strip each digit from f
and store it in an array using a loop and modulus (%).
for(int i=length-1; i >= 0; --i)
{
array[i] = f % 10;
f = f / 10;
}
Each time through the loop, the module takes the last digit, returning the remainder of the division by 10. The next line divides f
by 10 to prepare for the next iteration of the loop.
a source to share