How to put numbers of an integer in a vector in C++

Mohamed Ahmed picture Mohamed Ahmed · Apr 2, 2014 · Viewed 7.9k times · Source

If a user enters an integer like 4210 for example, how can I put each number of that integer in a vector in C++?

Answer

Nejat picture Nejat · Apr 2, 2014

It can be done like:

std::vector<int> numbers;
int x;
std::cin >> x;
while(x>0)
{
   numbers.push_back(x%10);
   x/=10;
}

std::reverse(numbers.begin(), numbers.end());