File Data Handling And Problem Solving Examples With C++

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.

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper

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

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper
  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).

What Will You Get?

We provide professional writing services to help you score straight A’s by submitting custom written assignments that mirror your guidelines.

Premium Quality

Get result-oriented writing and never worry about grades anymore. We follow the highest quality standards to make sure that you get perfect assignments.

Experienced Writers

Our writers have experience in dealing with papers of every educational level. You can surely rely on the expertise of our qualified professionals.

On-Time Delivery

Your deadline is our threshold for success and we take it very seriously. We make sure you receive your papers before your predefined time.

24/7 Customer Support

Someone from our customer support team is always here to respond to your questions. So, hit us up if you have got any ambiguity or concern.

Complete Confidentiality

Sit back and relax while we help you out with writing your papers. We have an ultimate policy for keeping your personal and order-related details a secret.

Authentic Sources

We assure you that your document will be thoroughly checked for plagiarism and grammatical errors as we use highly authentic and licit sources.

Moneyback Guarantee

Still reluctant about placing an order? Our 100% Moneyback Guarantee backs you up on rare occasions where you aren’t satisfied with the writing.

Order Tracking

You don’t have to wait for an update for hours; you can track the progress of your order any time you want. We share the status after each step.

image

Areas of Expertise

Although you can leverage our expertise for any writing task, we have a knack for creating flawless papers for the following document types.

Areas of Expertise

Although you can leverage our expertise for any writing task, we have a knack for creating flawless papers for the following document types.

image

Trusted Partner of 9650+ Students for Writing

From brainstorming your paper's outline to perfecting its grammar, we perform every step carefully to make your paper worthy of A grade.

Preferred Writer

Hire your preferred writer anytime. Simply specify if you want your preferred expert to write your paper and we’ll make that happen.

Grammar Check Report

Get an elaborate and authentic grammar check report with your work to have the grammar goodness sealed in your document.

One Page Summary

You can purchase this feature if you want our writers to sum up your paper in the form of a concise and well-articulated summary.

Plagiarism Report

You don’t have to worry about plagiarism anymore. Get a plagiarism report to certify the uniqueness of your work.

Free Features $66FREE

  • Most Qualified Writer $10FREE
  • Plagiarism Scan Report $10FREE
  • Unlimited Revisions $08FREE
  • Paper Formatting $05FREE
  • Cover Page $05FREE
  • Referencing & Bibliography $10FREE
  • Dedicated User Area $08FREE
  • 24/7 Order Tracking $05FREE
  • Periodic Email Alerts $05FREE
image

Services offered

Join us for the best experience while seeking writing assistance in your college life. A good grade is all you need to boost up your academic excellence and we are all about it.

  • On-time Delivery
  • 24/7 Order Tracking
  • Access to Authentic Sources
Academic Writing

We create perfect papers according to the guidelines.

Professional Editing

We seamlessly edit out errors from your papers.

Thorough Proofreading

We thoroughly read your final draft to identify errors.

image

Delegate Your Challenging Writing Tasks to Experienced Professionals

Work with ultimate peace of mind because we ensure that your academic work is our responsibility and your grades are a top concern for us!

Check Out Our Sample Work

Dedication. Quality. Commitment. Punctuality

Categories
All samples
Essay (any type)
Essay (any type)
The Value of a Nursing Degree
Undergrad. (yrs 3-4)
Nursing
2
View this sample

It May Not Be Much, but It’s Honest Work!

Here is what we have achieved so far. These numbers are evidence that we go the extra mile to make your college journey successful.

0+

Happy Clients

0+

Words Written This Week

0+

Ongoing Orders

0%

Customer Satisfaction Rate
image

Process as Fine as Brewed Coffee

We have the most intuitive and minimalistic process so that you can easily place an order. Just follow a few steps to unlock success.

See How We Helped 9000+ Students Achieve Success

image

We Analyze Your Problem and Offer Customized Writing

We understand your guidelines first before delivering any writing service. You can discuss your writing needs and we will have them evaluated by our dedicated team.

  • Clear elicitation of your requirements.
  • Customized writing as per your needs.

We Mirror Your Guidelines to Deliver Quality Services

We write your papers in a standardized way. We complete your work in such a way that it turns out to be a perfect description of your guidelines.

  • Proactive analysis of your writing.
  • Active communication to understand requirements.
image
image

We Handle Your Writing Tasks to Ensure Excellent Grades

We promise you excellent grades and academic excellence that you always longed for. Our writers stay in touch with you via email.

  • Thorough research and analysis for every order.
  • Deliverance of reliable writing service to improve your grades.
Place an Order Start Chat Now
image

Order your essay today and save 30% with the discount code ESSAYHELP