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);
}
Last edited on
6-digit number? imagine 6 file streams trying to open...
I.e., you need to open the output stream in main and pass it to your function by reference.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>

using namespace std;

void function(ofstream& fout, unsigned int n)
{
	if (n > 0)
	{
		fout << n % 10 << endl;
		function(fout, n / 10);
	}
}

int main()
{
	unsigned int n;
	ifstream fin("input.txt");
	fin >> n;
	ofstream fout("o.txt");
	function(fout, n);
}

Thank You!
Topic archived. No new replies allowed.