Get Instant Help From 5000+ Experts For
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing:Proofread your work by experts and improve grade at Lowest cost

And Improve Your Grades
myassignmenthelp.com
loader
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Guaranteed Higher Grade!
Free Quote
wave

What if the number of cars at the start of the file did not match the actual number in the file?

What code would you suggest to check for that?

Would you add some code to return an error value if LoadCars found a mismatch? Or would you add code elsewhere in the program eg FindNumCars?

Could you think of ways the program could cope if there were too few cars?

What about too many?

Checking for Mismatch in Car File Data

If during the following steps you cannot follow something, or it doesn't work, please check with your neighbour that you are doing it right. If it still doesn't work, raise your hand and the tutor will try to help.

NOTE! There will be a dropbox on NOW called Session8. You are EXPECTED to code for 8-10 hours per week outside class.

So put your programs in the dropbox (just the cpp files, not the whole folder) so that there is evidence of your activity BEYOND the lab.

Exercise 1 – file data handling

  • Download Session8.zip from NOW and unzip it into your folder
  • Double click the .sln (Visual Studio solution) file which will start up Visual Studio.

Part A – Reading a file of an arbitrary length

  1. Examine and run the program in Session8.cpp. It is a program to display the data from a set of cars – name of model, registration, engine size (in litres) and price as in Session7, using a struct for each car.
  2. NOTEthat there is NO CONSTANT called MAXCARS at the top! That is because the program will be working out how many cars we need to handle
  3. USEthe debugger – put a breakpoint at the line where the function FindNumCars is called. F5 to start debugging, then when the program stops at that line, use F11 to go INTO the function.
  4. Then use F10 repeatedly to step through the FindNumCars function.
  5. NOTEthat all it does is read the file line by line to count the lines (and ignore the contents!)
  6. SET UPanother breakpoint at the line in main where the memory is acquired from the heap (ie where the keyword new is used).
  7. USEF5 to get to this breakpoint.
  8. NOTE the value contained in StockList at this point, before the line is executed (ie 0xcccccccc) by looking in the bottom left pane (autos), or right click on it and use Quickwatch. This value shows that the pointer has not yet been allocated a value.
  9. PressF10 so that the line is executed. NOTE that there is now a sensible address in StockList.
  10. EXPAND the entry for StockList in the autos pane – note that some elements of car data (ModelName, Registration) are empty, while others (EngineSize, Price) show extreme values to indicate that they have not yet been set.
  11. Press F10 so that the LoadCars function is called and fills in the StockList.
  12. NOTE that the view of StockList in the autos pane only shows the first entry when expanded. To see the other elements of the array (which is accessible only via the pointer), we need to use quickwatch to get at specific elements as shown below for StockList[2] (typed into the Expression edit box):
  13. Press F10 repeatedly (SLOWLY!) to step through the display, then finding and displaying the most expensive, until the program is waiting to execute the line that frees the space back to the heap (delete [] StockList;).
  14. NOTE the details of StockList in the autos pane.
  15. Press F10 to execute the delete line.
  16. NOTE that the autos window now shows StockList contents in red, with the components as Bad Ptr. This indicates that the space is now unavailable to this program, and it is not safe to use StockList contents

Note also that this program is mainly carried out by calling functions, with very little else going on in main. Our aim is always to make the main program as clean as possible.

Part B – Proving that this method can cope with different file lengths…?

  1. COPYtxt to a backup called carsOld.txt.
  2. MODIFYtxt to add 3 more cars (8 in total). Ensure the LAST car in the file is the most expensive, and that there is no newline following the last car.
  3. RUNthe program again and verify that it finds and displays the new most expensive car, without you having to change ANY CODE.
  4. ADDa newline after the last car in the file cars.txt, and save the file.
  5. USEthe debugger – put a breakpoint at the line where the function FindNumCars is called. F5 to start debugging, then F10 to execute that function.
  6. HOVERthe mouse over NumCars. The number will be 9 instead of the expected 8 - one more than the number of cars in the file!
  7. PRESS F10 until the LoadCars function has been executed.
  8. USE quickwatch to examine StockList[7] – verify that this matches the last car you added.
  9. USEquickwatch to examine StockList[8] – verify that it contains empty strings and uninitialized values ie it is a valid car entry but has not got any data.
  10. USE quickwatch to examine StockList[9] – verify that it shows bad ptr – indicating that this chunk of memory space has not been acquired for this array.
  11. PRESSF10 to advance the program past the DisplayCars function – the console window should show not only the valid cars, but the extra entry with no names and uninitialised values for price and enginesize.

This shows the problem that can occur if an accidental newline is added at the end of the file.

Part C – Making the file reading safer

  1. In the function FindNumCars,  ADD CODEjust before the final return to do the following:

If the last line read (ie stored in tempLine) has a length of 0, decrement the counter value by one, since it should not have been incremented for that empty line.

  1. REMEMBERhow to find the length of a string – stringname.length() will return the number of characters for the string referred to by stringname
  2. USEthe debugger to check that FindNumCars now produces a value of 8.
  3. VERIFYthat the program now works correctly.
  4. CHANGEthe file cars.txt to get rid of the extra newline.
  5. RUNthe program again to verify that it still works with a file structured correctly!

Part D -  Doing it yourself

  1. Use the code you wrote over the last 2 weeks to handle an array of pets.
  2. Remove any declaration of const int MAXPETS or similar, and remove the fixed size declaration of the array of pets
  3. Add a function called FindNumPets as for FindNumCars that returns the size of the file when passed a filename
  4. In main, call FindNumPets, so that the returned value is saved to a variable called NumPets
  5. Declare a pointer to Pet and assign to it the space allocated from the heap for an array of Pets sized to hold NumPets
  6. Ensure that your file reading function and display function are called with the correct parameters (ie the name of the pointer and NumPets)
  7. Make sure that after all the use of the array, and just before the return 0in main, you free up the heap space by using
  8. Check that the program works
  9. Modify your text file to add 2 more pets, and verify that your program still functions correctly
  10. Now modify your text file so that it has a newline after the last pet. Check that your program behaves like the one earlier and shows a ‘fake’ entry because of the blank line.
  11. Modify your FindNumPets function so that it checks for the empty last line and decrements the counter.
  12. Verify that the program now handles this file correctly, and can still work when the file is returned to its original form.

Part E -  Doing it yourself again…

  1. Use the code you wrote over the last 2 weeks to handle an array of students with an array of marks.
  2. Repeat the work done above in Part D for the student array.

Part F – changing the way it works by changing the file format

In this stage we shall use a file with a counter at the start that specifies the number of entries, so that we don’t have to read the whole file twice.

  1. Exclude Session8.cpp from the project and instead include Session8_1.cpp.
  2. Build and run the program. Verify that it appears to work as before.
  3. Open the file cars2.txt and note the counter on the first line.
  4. Change the counter from 5 to 6 and add a new car at the end.
  5. Save the file.
  6. Set a breakpoint within FindNumCars, and get to it by pressing F5. Step through with F10, noting that all it does is read the first line then close the file.
  7. Before you exit the function, set another breakpoint in LoadCars. Press F5 to get to it.
  8. Step through LoadCars, noting that it deliberately reads the first line and discards it, then proceeds as before to read the rest of the file into the array.
  9. Note that the program correctly reads the new set of cars.

Discuss these problems with your tutor and see if you can add some error checking code.

Part G – changing your code to use the same structure

  1. Repeat the changes to the file format and the associated code to read/check the file in your pets program
  2. Verify that it works correctly
  3. Do the same to the students program.

Exercise 2 – Problem Solving Examples

Last week you were given a range of problems to solve – on paper first, and then writing the program. Here a few are visited again.

Part A – Finding largest integer

Write a program that prompts the user to enter a set of positive integers in any order (stopping when they enter 0). It then reports the highest number they entered. Do NOT use an array for the numbers.

Solution

The important idea in this problem is that we need a way of remembering the ‘current highest’ value. This is similar to the way we iterate through an array – except we are just comparing the latest value input against our ‘current highest’.

  1. Exclude Session8_1.cpp from the project, and include instead the file Session8_2.cpp.
  2. Note the structure of the program.
  3. Verify that it works for positive integers, but will not work if any of the integers are negative.

Making File Data Reading Safer

Note that since the problem specifies ‘positive integers’ only, we can initialize the ‘current highest’ to be zero. If the problem had just specified ‘integer’, then we would have had to use a FLAG to ensure that when the first number was entered, it was used to initialize the ‘current highest’.  We would also have to find a different way of ending the loop since we might want to include -1 as a possible integer.

So we have a version that can handle negative numbers, and relies on the user entering “Y” to finish. This is where we use stringstream to take input as a string, and then convert it to a number (if possible).

  1. Exclude Session8_2.cpp from the project, and include instead the file Session8_3.cpp.
  2. Run the program, specifying a sequence of numbers that include positive and negative integers, ending with a “Y”.
  3. Set a breakpoint in the program, and use F10 to step through it.
  4. Note that the way this handles input that may be a “Y” or an integer is via stringstream.

A stringstream is declared and initialised with the text as input. (stringstream valStr(valString);)

An attempt is made to send the stringstream to an integer, thus converting a string into an integer. (valStr >>currentValue)

If the conversion fails ie returns false, then we end the loop. (if (!(valStr>>currentValue))

IMPORTANT – the line where we check whether the highest has yet been set, or whether the currentValue is higher, HAS to check first for !highest.

The c++ ‘if’ does not test multiple conditions if the first one is already true. So this ordering is important, otherwise the ‘if’ will test currentHighest which has not yet been given a value – and will fail.

  • To show this, swap round the terms in the ‘if’:

else if ((currentValue>currentHighest) ||!highest)

  • Run the program – it should cause a fail

Part B – Dinner menus

A school has a dinner menu that repeats itself every 4 weeks. If the menus are denoted by week A,B,C,D, and the school year runs from week 1 to week 36, display a table that shows which menu is in each week of the year. To make this table more compact for printing, get it to print weeks 1 to 18 and their menus in 1 column, and weeks 19 to 36 in the next column.

Solution

We need to start by visualizing what is required. So first write out on paper what the dinners look like eg the one column version:

  • A
  • B
  • C
  • D
  • A
  • B
  • C
  • D etc etc

We know that we have to cycle around every 4 weeks – so if the week number is a multiple of 4 it is a D week, if the week number when divided by 4 has a remainder of 1 it is an A week. This obviously suggests the modulus operation (%)!

  • Exclude Session8_3.cpp and include Session8_4.cpp.
  • Verify that this produces a single column version of the display.
  • Note that it uses a LOOKUP array so that the display process is simpler.
  • Modify this program so that it writes the information to a text file (so the catering staff can print it!)

Now the program needs to be modified for 2 columns. Again, sketch out what the display would look like:

So the % operation still applies, but we now need to change the loop through the weeks so that it covers week 1+ week 19, week 2 + week 20, week N + week N+18…

This means the loop just goes from 1 to 18, displaying week N and week N+18 on each iteration, with the same modulus tests used on N and N+18 to decide what dinner letter to print.

  • Modify the program to do this, and check that the display now shows the 2 columns.
  • Add similar behaviourso that it saves to a file in the same way.
  • Change the program so that the file saving is done in a separate function.
  • Now consider a change to display this in 4 columns
  • Again sketch out what you want it to look like.
  • Since you will have 4 numbers to work out the letter for on every iteration (eg week 1, 10, 19, 28 together), then write a function that has a parameter of an integer (week number) and returns a char or string containing A, B, C or D by using the modulus operation.
  • Create a version of the program that runs for 40 weeks, and cycles through FIVE different dinners (A to E).
Cite This Work

To export a reference to this article please select a referencing stye below:

My Assignment Help. (2020). Essay: File Data Handling And Problem Solving Examples With C++.. Retrieved from https://myassignmenthelp.com/free-samples/soft10101-computer-science-programming.

"Essay: File Data Handling And Problem Solving Examples With C++.." My Assignment Help, 2020, https://myassignmenthelp.com/free-samples/soft10101-computer-science-programming.

My Assignment Help (2020) Essay: File Data Handling And Problem Solving Examples With C++. [Online]. Available from: https://myassignmenthelp.com/free-samples/soft10101-computer-science-programming
[Accessed 22 November 2024].

My Assignment Help. 'Essay: File Data Handling And Problem Solving Examples With C++.' (My Assignment Help, 2020) <https://myassignmenthelp.com/free-samples/soft10101-computer-science-programming> accessed 22 November 2024.

My Assignment Help. Essay: File Data Handling And Problem Solving Examples With C++. [Internet]. My Assignment Help. 2020 [cited 22 November 2024]. Available from: https://myassignmenthelp.com/free-samples/soft10101-computer-science-programming.

Get instant help from 5000+ experts for
question

Writing: Get your essay and assignment written from scratch by PhD expert

Rewriting: Paraphrase or rewrite your friend's essay with similar meaning at reduced cost

Editing: Proofread your work by experts and improve grade at Lowest cost

loader
250 words
Phone no. Missing!

Enter phone no. to receive critical updates and urgent messages !

Attach file

Error goes here

Files Missing!

Please upload all relevant files for quick & complete assistance.

Plagiarism checker
Verify originality of an essay
essay
Generate unique essays in a jiffy
Plagiarism checker
Cite sources with ease
support
close