If you always receive the number via some text input (command line or a text file) then there's no reason to do modulo arithmetic. If your loop is even tightly coupled to the number of symbols received, it makes even less sense to operate on the integer. Instead, receive the input as a string.
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a positive integer: ";
std::getline(std::cin, input);
for (int i = 0; i < input.length(); i++) {
std::cout << "Digit number " << i << " is " << input[i] << std::endl;
}
}
NOTE input[i]
is a character, and any arithmetic operations on that character will not work the same way you expect it to on the integer's individual digits. If you want the number to work with numerically (instead of just symbolically) you can convert to an integer using the std::stoi
family of functions ("string to integer").
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a positive integer: ";
std::getline(std::cin, input);
for (int i = 0; i < input.length(); i++) {
std::cout << "Digit number " << i << " is " << input[i] << std::endl;
}
int value = std::stoi(input);
std::cout << "The number times 2 is " << value * 2 << std::endl;
}
NOTE The std::stoi
family of functions provide error checking functionality. My above example omits that for simplicity, and because this sounds like a school assignment where input validation is the user's problem.