Reputation: 455
If a user enters an integer like 4210 for example, how can I put each digit of that integer in a vector in C++?
Upvotes: 7
Views: 17159
Reputation: 21
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;
}
Upvotes: 2
Reputation: 299790
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');
}
Upvotes: 2
Reputation: 4888
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.
Upvotes: 0
Reputation: 32635
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());
Upvotes: 10