Question

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

Was it helpful?

Solution

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());

OTHER TIPS

The Easiest way I found is this :

std::vector<int> res;

int c;
std::cin >> c;

while(c>0)

    {
    res.insert(res.begin(),c%10);
    c/=10;
    }

I don't understand why people advise such round about solutions as converting back and forth to int when all you want is digit by digit... for a number expressed in decimal by the user.

To transform "4321" into std::vector<int>{4, 3, 2, 1} the easiest way would be:

std::string input;
std::cin >> input;

std::vector<int> vec;

for (char const c: input) {
    assert(c >= '0' and c <= '9' and "Non-digit character!");
    vec.push_back(c - '0');
}

Or if you prefer using std::string you can use:

std::vector<int> intVector;

int x;
std::cin >> x;

for (const auto digit : std::to_string(x)) {
    intVector.push_back(digit - '0');
}

This assumes your compiler can use C++11.

Live example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top