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

If the user enters an integer, for example 4210, how can I put every number of this integer into a vector in C ++?

+4
source share
3 answers

This can be done like this:

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());
+5
source

Or, if you prefer to use 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.

Living example

0
source

, int, , , ... , .

"4321" std::vector<int>{4, 3, 2, 1}, :

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');
}
0
source

Source: https://habr.com/ru/post/1534696/


All Articles