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
- 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.
- 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
- 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.
- Then use F10 repeatedly to step through the FindNumCars function.
- NOTEthat all it does is read the file line by line to count the lines (and ignore the contents!)
- SET UPanother breakpoint at the line in main where the memory is acquired from the heap (ie where the keyword new is used).
- USEF5 to get to this breakpoint.
- 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.
- PressF10 so that the line is executed. NOTE that there is now a sensible address in StockList.
- 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.
- Press F10 so that the LoadCars function is called and fills in the StockList.
- 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):
- 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;).
- NOTE the details of StockList in the autos pane.
- Press F10 to execute the delete line.
- 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…?
- COPYtxt to a backup called carsOld.txt.
- 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.
- RUNthe program again and verify that it finds and displays the new most expensive car, without you having to change ANY CODE.
- ADDa newline after the last car in the file cars.txt, and save the file.
- USEthe debugger – put a breakpoint at the line where the function FindNumCars is called. F5 to start debugging, then F10 to execute that function.
- HOVERthe mouse over NumCars. The number will be 9 instead of the expected 8 - one more than the number of cars in the file!
- PRESS F10 until the LoadCars function has been executed.
- USE quickwatch to examine StockList[7] – verify that this matches the last car you added.
- 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.
- 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.
- 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
- 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.
- REMEMBERhow to find the length of a string – stringname.length() will return the number of characters for the string referred to by stringname
- USEthe debugger to check that FindNumCars now produces a value of 8.
- VERIFYthat the program now works correctly.
- CHANGEthe file cars.txt to get rid of the extra newline.
- RUNthe program again to verify that it still works with a file structured correctly!
Part D - Doing it yourself
- Use the code you wrote over the last 2 weeks to handle an array of pets.
- Remove any declaration of const int MAXPETS or similar, and remove the fixed size declaration of the array of pets
- Add a function called FindNumPets as for FindNumCars that returns the size of the file when passed a filename
- In main, call FindNumPets, so that the returned value is saved to a variable called NumPets
- Declare a pointer to Pet and assign to it the space allocated from the heap for an array of Pets sized to hold NumPets
- Ensure that your file reading function and display function are called with the correct parameters (ie the name of the pointer and NumPets)
- 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
- Check that the program works
- Modify your text file to add 2 more pets, and verify that your program still functions correctly
- 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.
- Modify your FindNumPets function so that it checks for the empty last line and decrements the counter.
- 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…
- Use the code you wrote over the last 2 weeks to handle an array of students with an array of marks.
- 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.
- Exclude Session8.cpp from the project and instead include Session8_1.cpp.
- Build and run the program. Verify that it appears to work as before.
- Open the file cars2.txt and note the counter on the first line.
- Change the counter from 5 to 6 and add a new car at the end.
- Save the file.
- 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.
- Before you exit the function, set another breakpoint in LoadCars. Press F5 to get to it.
- 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.
- 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
- Repeat the changes to the file format and the associated code to read/check the file in your pets program
- Verify that it works correctly
- 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’.
- Exclude Session8_1.cpp from the project, and include instead the file Session8_2.cpp.
- Note the structure of the program.
- 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).
- Exclude Session8_2.cpp from the project, and include instead the file Session8_3.cpp.
- Run the program, specifying a sequence of numbers that include positive and negative integers, ending with a “Y”.
- Set a breakpoint in the program, and use F10 to step through it.
- 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).
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 December 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 December 2024.
My Assignment Help. Essay: File Data Handling And Problem Solving Examples With C++. [Internet]. My Assignment Help. 2020 [cited 22 December 2024]. Available from: https://myassignmenthelp.com/free-samples/soft10101-computer-science-programming.