Hello, I would greatly appreciate it if anyone could help me clarify how to tackle "catching appropriate exceptions". I have two functions that currently store and output information to a file. I'm having trouble with catching invalid user input, would this be an appropriate example?
// Function that provides the ability to write to a file
void saveVector(string fileName, vector <Vehicle *> vehicles)
{
size_t i;
// Ask the user to provide a file name
cout << "Please provide a file name: ";
cin >> fileName;
//
ofstream newFile;
newFile.open("test.txt");
if (newFile.is_open())
{
// For each element in the vector
for (i = 0; i < vehicles.size(); i++)
{
// Store each vehicle element in the file
newFile << vehicles[i] << endl;
}
newFile.close();
}
else
{
cout << "Unable to create file" << endl;
}
}
// Function that provides the ability to read a file
void loadVector(string fileName, vector <Vehicle *> vehicles)
{
// Declare variables and file instance
size_t i;
string line;
ifstream newFile ("test.txt");
// Ask the user to enter a filename to load
cout << "Enter a current saved filename to read: ";
cin >> fileName;
cout << endl;
// Produce error checking for input loading
if (newFile.is_open())
{
cout << "File opened successfully" << endl << endl;
//newFile.open(fileName);
if (newFile.good())
{
// For each element in the vector
for (i = 0; i < vehicles.size(); i++)
{
// Call display function to print content in file
vehicles[i]->display();
}
}
newFile.close();
}
else
{
// Prompt user with error message
cout << "Incorrect file name, file opening failed." << endl;
}
}
Well, There are no "exceptions"(http://www.cplusplus.com/doc/tutorial/exceptions/) being thrown or caught here; when you say exceptions do you want to be using exceptions? Or just handling a bad file name? Because if it is just handling a bad file name, I'd say what you have is a good way to do that. Probably change newFile.open("test.txt"); to newFile.open(fileName.c_str()); though so that you open the file they input.
On a side note, if you're using fileName as a storage from cin, why pass it in as an argument; probably be better to just have it as a temporary variable in the function :P
Yeah you're right, I haven't implemented any exceptions at the moment. I assume you are right with handling a bad file name, as I am being asked to also "catch appropriate exceptions when reading from or writing to a file".
Thanks for your input, I will be sure to try that out. I can't think of any alternatives to meet that criteria. :)