Self Studying C++, Code will not compile issue

I am trying to write code for the following question:

Write the definition of a function named fscopy that does a line-by-line copy from one stream to another. This function can be safely passed two fstream objects , one opened for reading, the other for writing. In addition, it gets a bool argument that is true if the output lines are to be numbered, and another argument , an int that specifies line-spacing in the output . Assume that the input source is a text file consisting of a sequence of newline character -terminated lines. The function copies, line by line, the entire content of the data source associated with the first argument to the data target associated with the second argument . It returns the number of lines read in. If it the third parameter , the bool is true , every line that is output is preceded by a 6-position field holding the line number (an integer ) followed by a space and then the actual line. If the last argument , the int is 2 or more, it specifies the line spacing: for example, it is 3, there are two blank lines output after each line printed. These blank lines are NOT numbered.

The code needs to be written in C++ programming language. I only need the fscopy function code.

I am able to copy the input character by character, but I do not know how to do it line by line. I am not sure if my for loop for line spacing is correct. If the int is 2 or more, there should be more than one blank line spacing. For example if the int is 3, there should be two blank line of output before the next line of text.

Here is my code:


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
int fscopy(fstream &i, fstream &o, bool number, int spacing)
{
	char ch;
	int lineNo = 1;

	if(number==true)
	{ 
		cout << setw(6);
		cout << lineNo;
		cout << " ";
	}	
	while (i)
	{
	i.get(ch);
	if(i)
	{
		o.put(ch);
		if (ch == '\n')
		{
			lineNo++;
			if (spacing >= 2)
				for (int i=0; i<spacing; i++)
				{
					cout << endl;
				}
			else
			{
				cout << endl;
			}
			if(number==true)
			{
				cout << setw(6);
				cout << lineNo;
				cout << " ";
			}
		}		
	}
	}
	return lineNo;
}



Last edited on
I am able to copy the input character by character, but I do not know how to do it line by line.

It is often a good idea to read the documentation of functions that you use. For fstream Google would lead you to: http://www.cplusplus.com/reference/fstream/fstream/
If you read that you will find that there is a getline option.

In addition, I would like to recommend spending a couple more keystrokes on your variable names. If you get used to variables with a single-letter-name your code will become hard to read. Single-letter-names are usually only used for things like the index counters in small loops.
Topic archived. No new replies allowed.