Ofstream writing error?

Hello everyone, I am creating the simplest program. At the top I am including basic ifstream and ofstream objects to display the previous user, and enter new name to store into that file. If I manually save a name into the text file the ifstream is able to read and display it fine. So, I am pretty sure it has to do with the ofstream. Whenever i enter a name into ofstream it always creates a new file, but the text file doesnt store anything. It is simply empty. Here is the 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
41
42
43
 #include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;
using std::string;

int main()
{
	
	string name;

	//Read the previous user's name
	string line;
	ifstream myfile("pperson.txt");
	cout << "The last person to use this program was: ";
	if (myfile.is_open())
	{
		while (getline(myfile, line))
		{
			cout << line << '\n';
		}
		cout << "\n press enter to continue";
		
	}

	else cout << "Unable to open file" <<"\n press enter to continue";
	
	cin.get();

        user.close();

	//Introduction/ Get name to store file
	cout << "\n\nWelcome, please enter name to save file to: ";
	ofstream user; //writing to file
	string file;
	user.open("pperson.txt");
	getline(cin, file);
	cin.get();
	myfile.close();
	return 0;
}


It is also worth noting that in visual studio 2015 i get a weird message that says," the files has unsaved changes inside this editor and has been changed externally. Do you want to reload it? y or n?" I appreciate any advice,
Last edited on
I don't see you write to the file anywhere.
hey peter thanks for responding. I write on line 39 with getline and then cin "file" which is a string. I choose getline to take in more than one name but before i had it simply as cin >> file;

any ideas?
Ok, so you are reading a name and store it in a string variable named file. To write the content of file to the file you would have to write something like user << file;
Last edited on
Topic archived. No new replies allowed.