As you may know, this program is to inverse numbers (45 -> 54). However, there is a problem. With leading zeroes it does not work properly since integers ignore leading zeroes.
I read in Internet that to make this program work I should work with the text value and to do that I have to read the input into the string, then call std::reverse() and pass the string as input.
The problem is that I do not know how to do that. Can anyone teach me?
I cannot use any other library than iostream and string. Saying this because I saw other methods that use sstream library.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main () {
int n;
cin >> n;
int reverse = 0;
while (n != 0) {
int remainder = n%10;
reverse = reverse*10 + remainder;
n /= 10;
}
cout << reverse << endl;
}
s.cc: In function ‘int main()’:
s.cc:12:2: error: ‘reverse’ is not a member of ‘std’
std::reverse(str1.begin(), str1.end()); // Reverse beginning to end
^
error: ‘it’ does not name a type
for(auto it = s.rbegin(); it != s.rend(); ++it)
^
error: expected ‘;’ before ‘it’
for(auto it = s.rbegin(); it != s.rend(); ++it)
^
error: ‘it’ was not declared in this scope
push_back is just adding characters to the end of the string, we are going through string s in reverse order, adding each character to string rs as we go.
If you wanted you could write rs += *it; instead.
Iterators are similar to pointers, using * on 'it' gives you access to what 'it' refers to.