First, the loop you have to calculate how many digits there are in the number only works if the left-most digit is a 1
:
while (n != 1) // what if it's 2-9 instead?
{
n = n / 10;
counter++;
}
counter += 1;
The proper calculation would be
do {
n /= 10; // same as n = n / 10
++counter;
} while(n);
you must convert the input int to an int array
This requirement is pretty hard to fullfil using standard C++ since the sizes of arrays must be known at compile-time. Some compilers support Variable Length Arrays but using them makes your program non-portable. The tool for creating array-like containers with sizes only known at run-time is the class template std::vector
. In this case you want to use a std::vector<int>
. I've put the digit-counting part in a separate function here:
#include <iostream>
#include <vector>
int count_digits(int number) {
int counter = 0;
do {
number /= 10;
++counter;
} while (number);
return counter;
}
int main() {
int n;
if (!(std::cin >> n)) return EXIT_FAILURE;
// instead of int arr[ count_digits(n) ]; use a vector<int>:
std::vector<int> arr( count_digits(n) );
// fill the vector starting from the end:
for(size_t idx = arr.size(); idx--;) {
arr[idx] = n % 10; // extract the least significant digit
n /= 10;
}
// print the result using an old-school loop:
for(size_t idx = 0; idx < arr.size(); ++idx) {
std::cout << arr[idx] << '\n';
}
// print the result using a range based for-loop:
for(int value : arr) {
std::cout << value << '\n';
}
}
Alternatively, use a reverse iterator to fill the vector
:
for(auto it = arr.rbegin(); it != arr.rend(); ++it) {
*it = n % 10;
n /= 10;
}
You could also use the standard function std::to_string
to convert the int
to a std::string
(or read the value from the user as a std::string
directly).
Once you have a std::string
you can easily populate the vector<int>
by transformation.
Example:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
int main() {
int n;
if (!(std::cin >> n)) return EXIT_FAILURE;
auto as_str = std::to_string(n);
std::vector<int> arr(as_str.size()); // create it big enough to hold all digits
// transform each character in the string and put the result in arr:
std::ranges::transform(as_str, arr.begin(), [](char ch) { return ch - '0'; });
// print the result:
for (int x : arr) std::cout << x << '\n';
}