Now that weve had a taste of what file I/O is all about, heres your chance to try it out on your own!
Youre to write a program that will prompt the user if he/she would like to read ints from a file (and have them displayed to stdout) or write ints to a file for safekeeping. If the user wishes to save a set of numbers, then the file nums.txt is opened for writing and the user is prompted for integer values which are written to the output file. If the user decides to read the ints from nums.txt, then the file is opened and the integers it contains are extracted and displayed to stdout. If youd like to see some sample runs, take a look at ReadWriteIntsSampleRuns.txt. For this implementation, youll have to write a couple of other functions in addition to the main function:
WriteInts this function is called from main if the user wants to save a set of integers to the nums.txt file; it accepts as an input argument an opened output file stream object thats ready for writing. It then prompts the user for five integer values, each of which are written to the output file before returning back to the caller.
DisplayInts this function is called from main if the user wants to display the contents of nums.txt to stdout; it accepts as an input argument an opened input file stream object thats ready for reading. It proceeds to extract the five integer values and display them to stdout.
The main function will drive the whole program, itll be responsible for determining which function to call as well as the opening and closing of files. For more information, you may want to look in your book on p.308 for an introduction to file I/O, and a simple example on p.313 where the author demonstrates the.open and .close member functions you can call once youve declared an ifstream or ofstream variable. (However, dont forget to call the .fail function after you open the file so you can check if you were successful in opening the file; see p.316 for a brief discussion of that as well as a code sample!) Finally, on p.334 where the author points out that when you pass file stream variables as arguments to functions, they must be passed by reference.
Sample of Output:
Run #1: user attempts to read from a file that doesnt yet exist
Do you wish to R)ead or W)rite ints? r
Unable to open the input file
Run #2: user decides to save a set of ints to file nums.txt
Do you wish to R)ead or W)rite ints? w
Enter an int: 11
Enter an int: 22
Enter an int: 33
Enter an int: 44
Enter an int: 55
Run #3: user displays the contents of nums.txt to stdout.
Do you wish to R)ead or W)rite ints? r
11
22
33
44
55
Reviews
There are no reviews yet.