Paul Brammer
Paul Brammer

Reputation: 31

How to save data, user specified

this is a programme that needs to save the outputs to a user specified data file however it doesn't seem to save and Im not sure why, Im relatively new to C++ so any help is appreciated

cout << "Press 's' then 'Enter' to save the file or any other key then 'Enter' to display";
cin >> save;

if (save != 's')
{
    cout << "Ix = " << Ix << "A\n";
    cout << "Iy = " << Iy << "A\n";
    cout << "Vz = " << Vz << "V\n";
}
else
{
    cout << "Please enter a name for your file: \n";
    cin >> filename;

    cout << " Please enter a directory to save your file in: \n";
    cin >> filepath;

    ofstream file((filepath + "/" + filename).c_str());

//input is being writen to the file
    file << "Ix = " << Ix << "A\n";
    file << "Iy = " << Iy << "A\n";
    file << "Vz = " << Vz << "V\n";

    file << flush;
    file.close();
}

}

Upvotes: 1

Views: 67

Answers (1)

WolverinDEV
WolverinDEV

Reputation: 1524

welcome to SO.

When opening a file stream you first have to check whatever the opening operation has succeeded.
You could do it like this:

if(!file) { /* file isn't "good", open seems to have failed */}
/* or */
if(!file.good()) { /* file isn't good */ }

I guess, because its not writing anything to the file (nor creating the file?) the directory probably does not exists.
The std::ofstream class will not automatically create the required directories.
How you could create the required directories is well explained here: https://en.cppreference.com/w/cpp/filesystem/create_directory

Upvotes: 2

Related Questions