Problem with stream iterators

closed account (EwCjE3v7)
I have been given the following exercise from my book
Write a program that takes the name of an input and two output files. The input file should hold integers. Using an istream_iterator read the input file. Using ostream_iterator, write the odd numbers into the first output file. Each value should be followed by a space. Write the even numbers into the second file. Each of these values should be placed on a seperate line.


And I have one problem
My input file has the following
0 1 2 3 4 5 6 7 8 9

and odds output file has
9 
and the even output file has
8

How would I fix it?
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
26
int main()
{	
	ifstream numbersFile("input.txt");

	istream_iterator<int> getNumbers(numbersFile), eof;


	while (getNumbers != eof) {
		int num = *getNumbers++;
		ofstream out;
		ostream_iterator<int> storeOdds(out, " ");
		ostream_iterator<int> storeEvens(out, "\n");

		if (num % 2 == 0){
			out.open("even.txt");
			if (out.is_open())
				storeEvens = num; // problem is somewhere here
		} else {
			out.open("odd.txt");
			if (out.is_open())
				storeOdds = num; // problem is somewhere here
		}
	}

	return 0;
}
Last edited on
None of the code pertaining to opening/creating files and constructing iterators should be inside your loop.
1
2
3
out.open("odd.txt"); //Open file erasing all previous content
if (out.is_open())
	storeOdds = num;
You need to open file once. Just have 2 output file streams.

Bonus: using standard algorithms:

1
2
3
4
5
6
7
std::ifstream in("input.txt");
std::ofstream out_even("even.txt");
std::ofstream out_odd("odd.txt");
std::partition_copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
                    std::ostream_iterator<int>(out_even, " "),
                    std::ostream_iterator<int>(out_odd, "\n"),
                    [](int x) {return x % 2 == 0;})
Last edited on
closed account (EwCjE3v7)
Thank you cire and MiiNiPaa, guys at #cplusplus guided me through it so thank you and a thanks to them to.

@MiiNiPaa that bonus code is sweet mate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int main()
{	
	ifstream numbersFile("input.txt");

	istream_iterator<int> getNumbers(numbersFile), eof;

	ofstream outEven("even.txt");
	ofstream outOdd("odd.txt");
	ostream_iterator<int> storeEven(outEven, "\n");
	ostream_iterator<int> storeOdd(outOdd, " ");

	while (getNumbers != eof) {
		int num = *getNumbers++;

		if (num % 2 == 0){
				storeEven = num;
		} else {
				storeOdd = num;
		}
	}

	return 0;
}
Last edited on
Topic archived. No new replies allowed.