Recursion

Hello everyone! Here I have a code which should take an input from a file input.txt, for example an integer like 123456 and then using this recursion it should display the result to the output file o.txt which should be:
6
5
4
3
2
1
like this. It somehow works perfectly if in 12 line I use cout instead of fout, and display the result on the screen instead of the output file. Why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>

using namespace std;

void function(unsigned int n)
{
	ofstream fout;
	fout.open("o.txt");
	if (n > 0)
	{
		fout << n % 10 << endl;
		function(n / 10);
	}
}

int main()
{
	unsigned int n;
	ifstream fin;
	fin.open("input.txt");
	fin >> n;
	function(n);
}
You keep re-opening your output file.

You either need to close it each time and reopen it in append mode or open it once outside of function() and close it again after the recursive calls are complete.
Thanks!
Topic archived. No new replies allowed.