So I want to input something in a file but it doesn't seem to work. My code is this:
ofstream f("reservedTables.DAT");
cin >> table;
f.open("reservedTables.DAT", ios::out | ios::app);
f << table;
f.close();
What am I doing wrong? I write the number for the variable table but it doesn't appear in the file that I put it in
Quick walk through:
ofstream f("reservedTables.DAT");
Allocates stream and opens the file.
cin >> table;
Reads in input from user.
f.open("reservedTables.DAT", ios::out | ios::app);
Attempts to re-open the file. Will fail.
f << table;
Stream is in failed state after failed open and cannot be written.
f.close();
closes file.
Only open the file once and check for errors.
ofstream f("reservedTables.DAT", ios::app); // no need for ios::out.
// Implied by o in ofstream
cin >> table;
if (f.is_open()) // make sure file opened before writing
{
if (!f << table) // make sure file wrote
{
std::cerr << "Oh snap. Failed write".
}
f.close(); // may not be needed. f will automatically close when it
// goes out of scope
}
else
{
std::cerr << "Oh snap. Failed open".
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With