streaming/input/output program

closed account (Diz60pDG)
This is what I am trying to accomplish...

Write a program which reads a stream of numbers from a file and writes only the positive numbers to a second file. The user should be prompted to enter the names of both the input file and output file in main(), and then main() will open both files. Another function named process() must then be called to read all the numbers from
the input file and write the positive numbers to the output file. Note that you must pass
the open stream variables for each file as arguments to the process() function, and that you need to (always) double check that the files opened successfully before using them.


Here is the code I have come up with so far...I am unsure of what to do from here, am I on the right track?


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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void process(ifstream & in, ofstream & out);

int main()
{
	ofstream outf;
	ofstream inf;
	string inputfile;
	string outputfile;

	cout << "Enter the file name of the input file: ";
	cin >> inputfile;
	cout << "Enter the file name of the output file: ";
	cin >> outputfile;

	inf.open(inputfile);
	if (inf.fail())
	{
		cout << "File " << inputfile << " failed to open!" << endl;
		return 1;
	}

	
	outf.open(outputfile);
	if (outf.fail())
	{
		cout << "File " << outputfile << " failed to open!" << endl;
		return 1;
	}

	
	inf.close();
	outf.close();

	return 0;
}
	

void process(ifstream & in, ofstream & out)
{
	int i;

	while (in >> i)
	{
		if (i % 2 == 0)
			out << i;
	}

		}
You're definitely on the right track. My only comment is that process() is suppose to write the positive numbers. You're writing the even ones. Fix that and call process() from main() and you'll be all set.
Topic archived. No new replies allowed.