issues with file writing loop

Ok so I can get it to write a sentence to the file but im having issues looping it. I have it first create a file and write something in it then update the file within the loop until the user types "done". but its leaving off the first word and its not exiting when I type "done". Also if anyone has any advice on how to make the code shorter? That would be awesome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  void write()
{
	string input;
	ofstream biology_flash;
	biology_flash.open("C:\\Users\\Jack\\Desktop\\biology_flash_cards.txt");	//sort folder is created and opened.
	cin.ignore();
	getline(cin, input);
	biology_flash << input << endl;
	biology_flash.close();
	while (input != "done")
	{
		ofstream biology_flash;
		biology_flash.open("C:\\Users\\Jack\\Desktop\\biology_flash_cards.txt", ios::app);	//sort folder is created and opened.
		biology_flash << endl;
		cin.ignore();
		getline(cin, input);
		biology_flash << input << endl;
		biology_flash.close();
	}
}
Why are you opening and closing the file inside the loop? I suggest you get rid of lines 12 through 15 and line 9 and 18 and possibly line 6.




Yup, I think ive been looking at this for too long heh. It works perfectly now thanks!

updated code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void write()
{
	string input;
	ofstream biology_flash;
	biology_flash.open("C:\\Users\\Jack\\Desktop\\biology_flash_cards.txt");	//sort folder is created and opened.
	cin.ignore();
	getline(cin, input);
	biology_flash << input << endl;
	while (input != "done")
	{
		getline(cin, input);
		biology_flash << input << endl;
	}
	biology_flash.close();
}
You can probably get rid of line 14 as well. And you really should start getting used to using just the constructor when possible:

 
	ofstream biology_flash("C:\\Users\\Jack\\Desktop\\biology_flash_cards.txt");	//sort folder is created and opened. 


And don't forget if the user enters "done" for that first input you will write "done" to the file. And you might want to prompt the user telling them what they're entering. ie:

cout << "Please enter your input, enter "done" when finished: ";
Topic archived. No new replies allowed.