outputting information to a file

I am trying to create a void function that accepts an ofstream for the user to write lines of text to. The program will first prompt the user to enter a line of text, then the user will type a line and press enter, resulting in that line of text being written to the file. Here's the trick... the program will continue to prompt the user to write an additional line after each previous line was entered. The program will only stop prompting the user if the user presses enter twice in a row, the second time without any text.

The usage should look like this...
1
2
3
4
5
Enter a line of text: Sunny
Enter a line of text: Cloudy
Enter a line of text: Stormy
Enter a line of text:
End of program.


This is the code I have so far...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void write_lines(ofstream &out_file)
{

	int consecutive_newlines = 0;
	char symbol;
	cout << "Enter a line of text: ";
	while (consecutive_newlines != 2)
	{
		cin.get(symbol);
		out_file.put(static_cast<char>(symbol));
		if (symbol = '\n')
		{
			cout << "\nEnter a line of text: ";
			consecutive_newlines++;
		}
		else if (symbol != '\n' && consecutive_newlines > 0)
			consecutive_newlines = 0;
	}
}


consecutive_newlines keeps track of how many newline characters is read back-to-back. Once a newline has been found, the user is prompted to enter another line. If the user presses enter with no text, the loop should end, but it doesn't. I would really appreciate if anyone could help me solve this.

The most important part is that the function must write a newline character after each line of text and two consecutive newline characters immediately after the last line of text the user enters - this is why I am using in_file.get() and out_file.put(), so the program can recognize the newline characters.
Last edited on
any reason why you can't use strings?
I can't use any strings.. This exercise was given to us before we learned to use strings.
Well when I ran this and entered some text it simply printed line 13 twice then exited.
This is why I asked about strings, because getline() just makes life sooooo easy... Anyhoo there's something wrong, I'm only going to guess that it might be left over newlines in buffer (because there doesn't seem to be anything wrong with program logic). So cin.clear() should resolve this. Look it up.
I think I found the problem.. take a look at the if block condition - I used "=" instead of "==".
Last edited on
Topic archived. No new replies allowed.