Here's my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//variable init
ifstream inFile;
ofstream outFile;
string toPrint, fileName;
string var;
cout << "Enter your save file: "; cin >> fileName;//asks the file name
cout << "Searching..."<<endl;
string fileLocation = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";//locates it
inFile.open(fileLocation.c_str());
if(!inFile){//checks if the file is existent
cerr << "Error can't find file." << endl;
outFile.open(fileLocation.c_str());
outFile << "Player House: Kubo"<<endl;
outFile.close();
}
cout << "Loaded." << endl;
inFile.ignore(1000, ':'); inFile >> var; //gets the string and places it in variable named var
cout << var<<endl;
//replaces var
cout << "Enter a string: ";
cin >> var;
//saving
outFile.open(fileLocation.c_str());
outFile << "Player House: " << var;
inFile.close();
outFile.close();
}
Problem here is that I can't get the player's house named "Kubo" and place it in variable named "var". It manages to create the file in my documents and manages to change the variable in the replaces var section.
From what I understood, you need to simultaneously read and write a file. Try this code
I used
tellg()
to determine whether file is empty, you could also go with