Passing a file to a function

I have a question about passing a data file into a function.
I want the user to enter data.txt, which is the file that holds the data for the program. My problem is when I run the program I can input anything into the variable filename via the cin statement and the program will execute.

How do I use filename in the LoadData function?

void LoadData(string filename);
int main()
{
......
cout<<"Please input the data file: ";
cin>>filename;
LoadData(filename);
......
}

void LoadData(string filename)
{

ifstream inFile; // declare file stream variable
inFile.open( "data.txt" ); // open file from disk

int num = 0; // counter to increment index of arrays
while( !inFile.eof() )
{
inFile >> weight[ num ]; // input weight from file
inFile >> year[ num ]; // input year from file
inFile >> month[ num ]; // input month from file
inFile >> day[ num ]; // input day from file
num++;
}

inFile.close(); // close file

}
Pass filename.c_str() to the file stream open method
Thanks Bazzy. That was easy enough.
One more question.
In this LoadData function if the string "data.txt" was not entered correctly or it was anything but "data.txt" I have the following code to catch it:

if( !inFile )
{
cout << "Cannot open file.";
}
When the above occurs it outputs "Cannot open file."and the program stops.
From my understanding the stream enters a fail state and all output is stopped. In a function like this that returns void how do I deal with the fail state and continue the program?
if you want to quit a void function, simply call return; ( as you would do for a value-returning function but without any value )
Thanks again Bazzy. I got it!
Topic archived. No new replies allowed.