Reputation: 1
The following is my code.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
string name;
int main()
{
vector<string> authors {};
cout << "Add Author Name:\n";
cin >> name;
authors.push_back(name);
ofstream file;
file.open("data\\authors.txt");
file << name;
file.close();
return 0;
}
When I go to the directory that the file is set, there is no file with the authors name. Is there a way to get the file to save? I’m trying to program a sort of cataloguing program for a personal library, just an easy beginner project.
Upvotes: 0
Views: 61
Reputation:
Create an if
statement around your code for the file to check if it actually opened correctly, otherwise you might not know, and in your case that's probably what happened.
ofstream file;
file.open("data\\authors.txt");
if (file.is_open()) // <-- add this
{
file << name;
file.close();
}
Also, in regard to your question about how to save when you do file I/O, meaning reading and writing, once you close your file then your changes are automatically saved because you wrote to the file.
Upvotes: 1