Files shouldn't be too different from
cin and
cout. The entire C++ I/O library is designed based on the concept of a 'stream' of bytes. Whether that 'stream' comes from the user tapping keys from the keyboard into the keyboard buffer, or from files on a disk, or even from some other device, the syntax and way you handle that data is the same; The only extra step with a file is ensuring sure that file has been opened when you read from it.
A file ought to be slightly more predictable than user input from the keyboard, which means you can loop through a file grabbing multiple bits of data at a time before your program needs to do anything with that data. Files are sequential, so you always start at the beginning and finish at the end. Which means, if you want line 5 of the file, you need to have read lines 1,2,3 and 4 first.
- There's absolutely no "random access" here - this is why file handling almost always involves a loop somewhere.
- In your case, it looks like you want to read 4 lines of a file in order to construct a record about a person. (The record part is where your struct will come in, though you can build and test the struct without any file or user I/O whatsoever - and i strongly recommend doing it this way, since I/O always adds complexity to a program)
if you've not played around with strings before, look up the
<string> library. C++'s
string type is designed to be easy to use. Many of the operations you can do with integers, can also be done with strings (such as comparing, copying, etc).
You might want to forget enum's for the moment (They can't help you with file input anyway) - see if you can get your program to read a line of text from your file using the getline function - Remembering that the file syntax is exactly the same as for cin.
CODE
string mystring;
getline( cin, mystring );
Once you read a line from the file as text, its up to you to turn it into something meaningful to your program. eg, copying a Person's name into a name variable, and converting a date string into 3 separate numbers - String manipulation is a pretty big topic, you may decide that the layout of the data in your file needs to change in order to make life easier when reading data with your program.
This post has been edited by Bench: 16 Dec, 2007 - 12:36 PM