May 4th, 2013, 11:51 PM
Need a little help on C++ file reading
I was given these instructions for my college programming assignment, and I have done parts 1 and 2, and am having trouble on part three.
1. Use a function named PromptUser() to ask the user for a filename. It will return the
filename as a string object.
2. Open the filename for reading. If you cannot open the filename given, prompt the
user for another. Repeat this until you can open the user's file.
3. Use a function named ReadData() that will take a reference to an integer vector as
the first parameter and a reference to a file stream as the second parameter. It will
make sure the stream is open, then read all the data from the stream and place that
data into the vector. If the file is not open at the beginning of the function, the
function will return a 1, otherwise it will return 0. The main program should check
the return value of this function. If there is an error, give the user an error message
and then end the program.
Our professor gave us the functions, just without the definitions. So far this is what I have
I have no idea where to begin on the second method. Any help is appreciated, thanks a ton.
bool working = true;
while(working == true)
cout << "Please enter a file name: " << endl;
cin >> filename;
cerr << "Could not open: " << filename << endl;
working = false;
int ReadData(vector<int>& theData, ifstream& in)
May 5th, 2013, 07:15 AM
Re: Need a little help on C++ file reading
The function PromptUser will exit if an incorrect filename is entered (exit(1) after the cerr statement) rather than re-prompt the user for a file name. It would also be better if PromptUser had as a parameter a reference to a file stream. That way PromptUser could return the reference to the correctly opened file stream that could be directly used in ReadData. If PromptUser doesn't have the file stream reference parameter then the main program is going to have to open the returned file and check that it's valid - which has just been done in PromptUser!
Also, the ifstream constructor does not take a type of string, but a type of char *. So you will need
For your part 3, the first thing you need to do is to check that the ifstream is valid and the file open. Then you'll need to set the file pointer to the beginning of the file (.seekg(..)) then loop reading the data into an integer and add the integer to the vector (.pushback(..)) until there is an error on the file stream. EOF indicates all data in file read, while an error that is not EOF indicates that a non-integer has been found in the file.
Hope this helps. Good luck!
All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.