In your code, this line is problematic: n=n*10+r;
Since n
was not given an initial value, the result of the right side expression is likely not what you think it is.
And as stated, integer types can't have leading zeroes. So trying to build a reversed int
is not going to work.
There are a ton of ways to go about doing this. Unfortunately, you chose a method that can't work.
What comes to mind first is recursion.
#include <iostream>
void print_reversed(int n) {
int next = n / 10;
std::cout << n % 10;
if (next != 0) {
print_reversed(next);
} else {
std::cout << '\n';
}
}
int main() {
int number;
std::cout << "Input: ";
std::cin >> number;
print_reversed(number);
}
Note that the recursive solution only prints one digit at a time. Leading zeroes are not an issue.
Or, take the input as a string.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string number;
std::cout << "Input: ";
std::getline(std::cin, number);
/*
* Ideally you would validate the string before continuing.
*/
std::ranges::reverse(number);
std::cout << number << '\n';
}
std::ranges::reverse()
requires C++20. There is a version you can call that takes a pair of iterators in earlier standards.
Or, break the number into its digits and store them in a container for printing.
#include <iostream>
#include <vector>
int main() {
int number;
std::cout << "Input: ";
std::cin >> number;
std::vector<int> digits;
while (number != 0) {
digits.push_back(number % 10);
number /= 10;
}
for (auto i : digits) {
std::cout << i;
}
std::cout << '\n';
}
Note that the digits are automatically stored in reverse order; there is no need to do anything after breaking it apart.
My preference is the recursive solution, with "input as a string" as a close second. I wouldn't really use this third method, but it still works.
For all three solutions, if I enter 10
, the print-out is 01
.