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

1
2
int number = 567;
vector <int> 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.

Thanks in advance.
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:
1
2
3
4
5
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{
	std::vector<int> 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<<myvector[i]<<std::endl;
}
getchar();
return 0;
}

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.