Ifstream code is not placing the input into the variable

274 views Asked by At

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.

1

There are 1 answers

5
Shreevardhan On BEST ANSWER

From what I understood, you need to simultaneously read and write a file. Try this code

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string fileName;
    cout << "Enter your save file: ";
    cin >> fileName;
    string filePath = "C:\\Users\\CraftedGaming\\Documents\\" + fileName + ".txt";
    fstream file(filePath, fstream::in | fstream::out | fstream::trunc);   // open modes to read and write simultaneously
    string var;
    if (file.tellg() == 0)
        file << "Player House: Kubo\n";
    file.seekg(14);
    file >> var;
    cout << var << endl;
    file.close();
    return 0;
}

I used tellg() to determine whether file is empty, you could also go with

file.peek() == ifstream::traits_type::eof();