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:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
usingnamespace 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,
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;
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;