HW09: Read/Write File Ints Solved

25.00 $

Categories: ,
Click Category Button to View Your Next Assignment | Homework

You'll get a download link with a: zip solution files instantly, after Payment

Securely Powered by: Secure Checkout

Description

5/5 - (3 votes)

Now that we’ve had a taste of what file I/O is all about, here’s your chance to try it out on your own!

You’re 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 you’d like to see some sample runs, take a look at ReadWriteIntsSampleRuns.txt. For this implementation, you’ll 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 that’s 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 that’s ready for reading. It proceeds to extract the five integer values and display them to stdout.

The main function will drive the whole program, it’ll 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 you’ve declared an ifstream or ofstream variable. (However, don’t 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 doesn’t 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

  • IO.zip