### Putting an integer number into a vector

Hi everyone,

I have an int of several digits and i want to put that number into a vector where the all the digits are in separate elements. For example if i have

 ``12`` ``````int number = 567; vector myvector;``````

I would like the zeroth element of myvector to contain 5, the first element to contain 6, and the second element to contain 7.

Last edited on
You'll need an algorithm to split the number into its digits. Since integer division always rounds down, something like this will do:
 ``12345`` ``````for(unsigned int i = 100; i > 0; i/=10) { myvector.push_back(number/i); number -= (number/i)*i; }``````
Oh ok, i didn't think of that, but i tried your algorithm and it didn't work, but i get the idea.

thankyou
 ``12345678910111213141516`` ``````int main() { std::vector myvector; int number = 519; for(unsigned int i = 100; i > 0; i/=10) { myvector.push_back(number/i); number -= (number/i)*i; } for(size_t i = 0; i < myvector.size(); ++i) { std::cout<

This works for me. Just remember that if your number is longer than 3 digits i has to be initialized to something bigger.
You can determine the number of digits in your number with this piece of code:

`int digits = log10((float)number) + 1`

That way, you don't need to initialize anything as it will just work.
Topic archived. No new replies allowed.