How to convert a number into an array of single digit integers?

The input should be a number (entered in one line) like 83809684986986904 (the number is not less than 13 digits and not more than 10^5 digits). I want to make an integer array (not char because I'll use the single digits for arithmetic operations) containing single digit integers out of this number. So in this case, arr[0] = 8, arr [1] = 3 and so on. How can I achieve this?
Last edited on
Something that is 10^5 digits long is not going to be stored in an integer, so it must be input as a string (or be added directly a vector through stream.get() loop).

To convert each char in the string to an integer, you can do int digit = str[i] - '0';

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    string input;
    getline(cin, input);
    
    vector<int> digits(input.size());
    for (size_t i = 0; i < digits.size(); i++)
    {
        digits[i] = input[i] - '0';
    }
    
    for (size_t i = 0; i < digits.size(); i++)
    {
        cout << digits[i];   
    }
    cout << '\n';
}
Last edited on
As an example to convert input string to vector of digits, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
	std::string input;
	std::vector<unsigned> digits;

	std::cout << "Enter number: ";
	std::getline(std::cin, input);
	std::transform(input.begin(), input.end(), std::back_inserter(digits), [](char ch) {return ch - '0'; });
	std::copy(digits.begin(), digits.end(), std::ostream_iterator<unsigned>(std::cout, ""));

	std::cout << '\n';
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
   string input;
   cout << "Enter number: ";   getline( cin, input );
   vector<unsigned> digits( input.begin(), input.end() );
   for ( auto &i : digits ) i -= '0';
   
   for ( auto i : digits ) cout << i;
}
Topic archived. No new replies allowed.