# 如何在 C++ 中将整数转换为其数字的数组How to convert an integer to an array of its digits in C++

``````    A[0]=1
A[1]=0
A[2]=0
A[3]=4
``````

## 5 个回复5

### #1楼 票数：1

``````1004 % 10 = 4
1004 / 10 = 100
``````

### #2楼 票数：1

``````int originalNumber = 1004;
int digitArray[10] = {0};
int idx = 0;

while (originalNumber > 0)
{
int digit = n % 10;
originalNumber /= 10;
digitArray[idx] = digit;
++idx;
}

// Reverse the order of the array
std::reverse(std::begin(digitArray), std::begin(digitArray)+(idx-1));
``````

### #3楼 票数：0

``````#define SIZE 4

int* numToArray(int num)
{
int* arr = new int[SIZE]; // assuming you already know the number of digits in the number
for(int i = SIZE-1; i >= 0; i++)
{
arr[i] = num % 10; // Enters the last digit to the array
num /= 10; // Gets rid of the last digit in the number
}
return arr;
}
``````

### #4楼 票数：0

``````#include <iostream>
#include <vector>

int main() {
int number = 1004;
std::vector<int> digits;

while (number != 0) {
digits.insert(digits.begin(), number % 10);
number /= 10;
}

for (auto const i : digits) {
std::cout << i << " "; // 1 0 0 4
}

// or by index

std::cout << std::endl;

std::cout << "[0]" << digits[0] << std::endl; // 1
std::cout << "[1]" << digits[1] << std::endl; // 0
std::cout << "[2]" << digits[2] << std::endl; // 0
std::cout << "[3]" << digits[3] << std::endl; // 4

return 0;
}
``````

### #5楼 票数：0

``````#include <string>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
auto number = 1004;
auto asString = std::to_string(number); //
std::vector<int> digits(asString.length());
std::transform(asString.begin(), asString.end(), digits.begin(), [](char c){return c -'0';});

for(auto d : digits)
{
std::cout << d << ' ';
}
}
``````

2回复

1回复

3回复

2回复

3回复

2回复

2回复

4回复