Reverse digits

I use the following algorithm to display the reverse digits.
However, after I input an integer (actually a series of char), the program does not display them "continuously".
I have to type enter to display every digit.
What is the problem I have made?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
	char x;
	static int i = 0;
	
	if	(i++ == 0)
		cout << "Input an integer to reverse it: ";
	
	while	((x = cin.get()) != '\n')
	{
		main();
		cout << x;
	}
}


For example,
Input an integer to reverse it: 165
5
6
1


What I expect is the following
Input an integer to reverse it: 165
561
To my knowledge, in C++ it is forbidden to call main().

Since you are not even reading an integer to begin with, a plain solution would be to read a string then reverse it.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string s;

    std::cout << "Input a `number': ";
    std::getline(std::cin, s);
    std::reverse(s.begin(), s.end());
    std::cout << s << std::endl;
}


If you want to do this recursively, do not call main().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

void read_and_print()
{
    char x;

    if ((x = std::cin.get()) != '\n')
    // read some more
        read_and_print();

    std::cout << x;
}

int main()
{
    std::cout << "Input a `number': ";
    read_and_print();
    std::cout << std::endl;
}
Last edited on
Thanks. It works.
I like recursion because it's amazing.
Topic archived. No new replies allowed.