Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 400
Mohamed Ahmed Avatar asked Apr 02 '14 17:04

Mohamed Ahmed


People also ask

How do you store digits of a number in a vector?

Simplest would be to input it as a string and then just iterate that string, pushing every element into a vector. After you have each digit separately it's trivial to lexically cast it to integer for vector<int>.

How do you add numbers to an array?

An array is created using square brackets ( [ and ] ). For example, an array of numbers can be created as follows: let arr: number[] = []; To create an array of values, you simply add square brackets following the type of the values that will be stored in the array: number[] is the type for a number array.

Is an integer a vector?

There are two types of vectors: Atomic vectors, of which there are six types: logical, integer, double, character, complex, and raw. Integer and double vectors are collectively known as numeric vectors.


1 Answers

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());
like image 165
Nejat Avatar answered Nov 01 '22 14:11

Nejat