Question

can you please follow all the instructions ? The answers that I got has either missing...

can you please follow all the instructions ? The answers that I got has either missing range for loop or one funtion .

Read the instructions carefully. At least 10% will be deducted if the instructions are not followed.


For general lab requirements, see General Lab Requirements.

Do not prompt the user for input during the execution of your program. Do not pause at the end of the execution waiting for the user's input.

Notes

1. Your program should use named string constant for the file name to open the file. Do not add any path to the file name because the path on your computer is not likely to exist on the computer the instructor uses to grade the program. Points may be deducted if you don't follow this instruction.

2. Split statements and comments longer than 80 characters into multiple lines and use proper indentations for the split portions.

3. You should not use "break" or "continue" in your code.

4. You should not return from the middle of a function.

5. When you need to cast a variable to a different type, don't use the C-style casting. For example, (char *)ptr will not be accepted.

(Lab2b.cpp) This program has two parts. The first part is to produce a set of nutrition data and save it to a file in binary format. The second part of the program retrieves a certain nutrition data from the binary file.

The program must be written in accordance to the following plan:

Define Data Structure

Define a data structure named NutritionData that contains these fields

foodName (array of 40 char) , use an all uppercase integer constant identifier for the size.

servingSize (double)

calFromCarb (double)

calFromFat (double)

calFromProtein (double)

totalCalories (double)

Use the data types in parentheses for the fields.

Write necessary function prototypes. You should have at least the following two functions:

- A function that can save an array of NutritionData to a binary file. The function returns true if the binary file has been created and the data has been written to the file. Otherwise it returns false. Choose a meaningful identifier in camelCase for the function. For parameters, see the definition description below.

- A function that can retrieve and return a certain nutrition data record from a binary file. The function returns true if the record has been retrieved; otherwise it returns false. Choose a meaningful identifier in camelCase for the function. For parameters, see the definition description below.

Write the main Function

Define a string constant for the file name. The constant identifier should be all uppercase. The file name shall be called "nutrition.dat". The constant identifier should be used every time the file name is needed in the main function.

Define and initialize an array of NutritionData using the following data:

Apples raw, 110, 50.6, 1.2, 1.0

Bananas, 225, 186, 6.2, 8.2

Bread pita whole wheat, 64, 134, 14, 22.6

Broccoli raw, 91, 21.9, 2.8, 6.3

Carrots raw, 128, 46.6, 2.6, 3.3

Each record of data contains these fields: food name, serving size in grams, calories from carb, calories from fat and calories from protein.

Use a range-based for loop to iterate through the array of NutritionData and update the totalCalories field of each nutrition data. A range-based for loop that can update the array element values has a syntax like this:

for (auto &element: arrayName) {

}

Call the function that can save the array of NutritionData to "nutrition.dat".

If the call was successful, call the function that can retrieve a nutrition data record to retrieve the third record from "nutrition.dat".

If the call was successful, display the retrieved record. Otherwise, print "The desired structure cannot be extracted."

Write Function Definitions

- For the function that can save an array of NutritionData to a binary file.

The function should have the following parameters:

A parameter for the file name. This can be a const string reference parameter.

A pointer parameter that points to a NutritionData which is the first element in an array of NutritionData.

A parameter for the number of NutritionData in the array.

Parameters should be in camelCase. The function returns true if the array of NutritionData has been successfully save to the file, otherwise it returns false.

If the file already exists, print the message, "The file filename is an existing file. You can either delete the file or move it to another location and then run the program again." Replace the word filename with the value of the file name parameter.

If the file doesn't exist already, create a binary file for output using the file name parameter.

Write the array of NutritionData passed in through parameters to the file in binary format.

Close the file.

The function returns true if the file has been opened successfully and all records have been written to the file. Otherwise, it should return false. Therefore, you need to have code that tests the status of the file for success or error at each file operation.

- For the function that can retrieve a nutrition data.

The function should have the following parameters:

A parameter for the file name. This can be a const string reference parameter.

A reference parameter for returning the retrieved NutritionData.

A parameter for the desired structure. It must be a positive integer. If the value is 1, the function will attempt to return the first structure on file. If the value is 2, the function will attempt to return the second structure on file. And so on.

Parameters should be in camelCase. The function returns true if the desired record has been successfully retrieved from the file, otherwise it returns false.

Open the file as an input binary file using the file name parameter.

If the file doesn't exist, print the message, "The file filename cannot be opened." Replace the word filename with the value of the file name parameter.

If the file exists, access the desired record from the file. The program should use the seek mechanism to access the desired record. Note that the first record is at offset 0, the second record is at the offset that equals the size of a record, etc.

Read the desired record and store that in the passed NutritionData parameter.

Close the file.

The function returns true if the file has been opened successfully and the desired record has been retrieved and stored in the parameter. Otherwise, it should return false. Therefore, you need to have code that tests the status of the file for success or error at each file operation.

Test The Program

The output should look exactly as follows:

Food Name: Bread pita whole wheat
Serving Size: 64.0 grams
Calories Per Serving: 170.6
Calories From Carb: 134.0
Calories From Fat: 14.0
Calories From Protein: 22.6
0 0
Add a comment Improve this question Transcribed image text
Answer #1

The Required code is given below:-

//---------------------------------------------------------------------------------------------------------------------------------------

#include
#include

using namespace std;

struct NutritionData
{
   char foodName[40];
   double servingSize;
   double calFromCarb;
   double calFromFat;
   double calFromProtein;
   double totalCalories;
};

bool storeFoodList(const char*filename,NutritionData*list,int num);
bool retrieveFood(const char*filename,NutritionData&food,int n);

int main(int argc,char**argv)
{
   bool success=false;
   struct NutritionData food;
   const char* FILE_NAME = "nutrition.dat";
   struct NutritionData foods[5] = { {"Apples raw",110,50.6,1.2,1.0},
                                   {"Bananas",225,186,6.2,8.2},
                                   {"Bread pita whole wheat",64,134,14,22.6},
                                   {"Broccoli raw",91,21.9,2.8,6.3},
                                   {"Carrots raw",128,46.6,2.6,3.3}
                                   };
   for(auto &food:foods)
   {
       food.totalCalories=food.calFromCarb+food.calFromFat+food.calFromProtein;
   }
   success = storeFoodList(FILE_NAME,foods,5);
   if(success)
   {
       success=retrieveFood(FILE_NAME,food,3);
   }
   if(success)
   {
       cout<<"Food Name: "<        cout<<"Serving Size: "<        cout<<"Calories per Serving: "<        cout<<"Calories from Carb: "<        cout<<"Calories from Fat: "<        cout<<"Calories from Protein: "<    }
   else
   {
       cout<<"The desired structure cannot be extracted."<    }
   return 0;
}

bool storeFoodList(const char*filename,NutritionData*list,int num)
{
   ofstream fw;
   bool flag=true;
   fw.open(filename);
   if(fw.fail()) {
       cout<<"The file filename is an existing file. You can either delete the file or move it to another location and then run the program again."<        flag=false;
   }
   else
   {
       // create a new file here
       for(int i=0;i        {
           fw.write((char*)&list[i],sizeof(list[i]));
       }
   }
   fw.close();
   return flag;
}

bool retrieveFood(const char*filename,NutritionData&food,int n)
{
   ifstream fr;
   bool flag=true;
   fr.open(filename);
   if(fr.fail()) {
       cout<<"The file filename cannot be opened."<        flag=false;
   }
   else
   {
       // create a new file here
       fr.seekg((n-1)*sizeof(food),ios::beg);
       fr.read((char*) & food,sizeof(food));
   }
   fr.close();
   return flag;
}

Add a comment
Know the answer?
Add Answer to:
can you please follow all the instructions ? The answers that I got has either missing...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • c++ program Notes 1. Your program should use named string constant for the file name to open the file. Do not add any pa...

    c++ program Notes 1. Your program should use named string constant for the file name to open the file. Do not add any path to the file name because the path on your computer is not likely to exist on the computer the instructor uses to grade the program. Points may be deducted if you don't follow this instruction. 2. Split statements and comments longer than 80 characters into multiple lines and use proper indentations for the split portions. 3....

  • The name of the C++ file must be search.cpp Write a program that will read data...

    The name of the C++ file must be search.cpp Write a program that will read data from a file. The program will allow the user to specify the filename. Use a loop that will check if the file is opened correctly, otherwise display an error message and allow the user to re-enter a filename until successful. Read the values from the file and store into an integer array. The program should then prompt the user for an integer which will...

  • C Language program. Please follow the instructions given. Must use functions, pointers, and File I/O. Thank...

    C Language program. Please follow the instructions given. Must use functions, pointers, and File I/O. Thank you. Use the given function to create the program shown in the sample run. Your program should find the name of the file that is always given after the word filename (see the command line in the sample run), open the file and print to screen the contents. The type of info held in the file is noted by the word after the filename:...

  • C++ 1. Your program should use named string constant for the file name to open the...

    C++ 1. Your program should use named string constant for the file name to open the file. Do not add any path to the file name because the path on your computer is not likely to exist on the computer the instructor uses to grade the program. Points may be deducted if you don't follow this instruction. 2. Split statements and comments longer than 80 characters into multiple lines and use proper indentations for the split portions. (Lab2b.cpp) Write a...

  • in C++ and also each function has its own main function so please do the main...

    in C++ and also each function has its own main function so please do the main function as well. Previously when i asked the question the person only did the function and didn't do the main function so please help me do it. 1-1. Write a function that returns the sum of all elements in an int array. The parameters of the function are the array and the number of elements in the array. The function should return 0 if...

  • I need help with this assignment in C++, please! *** The instructions and programming style detai...

    I need help with this assignment in C++, please! *** The instructions and programming style details are crucial for this assignment! Goal: Your assignment is to write a C+ program to read in a list of phone call records from a file, and output them in a more user-friendly format to the standard output (cout). In so doing, you will practice using the ifstream class, I'O manipulators, and the string class. File format: Here is an example of a file...

  • T F a) Void Functions can use reference parameters. T F b) Arguments corresponding to reference p...

    T F a) Void Functions can use reference parameters. T F b) Arguments corresponding to reference parameters can be variables only T F c) The C++ statement retum "hello can be used with an integer value-retuming function T F d) Static variables maintain their value from function call to function call. T F e) The components of a C++ array must be homogeneous T F fA hierarchical structure has at least one component that is itself a structure. T F...

  • I need help with the following code... Instructions: This lab builds on the skills from Lab...

    I need help with the following code... Instructions: This lab builds on the skills from Lab 2c, in which you read data values from a file and kept a count of the number of invalid values. In this lab, your program will be using the same code to read each data entry from the file, but you will also save each value in an array named allMags after each is read in. When all values in the file have been...

  • I am having a little trouble with my Python3 code today, I am not sure what...

    I am having a little trouble with my Python3 code today, I am not sure what I am doing wrong. Here are the instructions: and here is my code: update: I have seen I did not close x in sumFile and I am still only getting a 2/10 on the grader. any help appreciated. Lab-8 For today's lab you going to write six functions. Each function will perform reading and/or write to a file Note: In zybooks much like on...

  • Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a funct...

    Program in C++! Thank you in advance! Write a menu based program implementing the following functions: (1) Write a function that prompts the user for the name of a file to output as a text file that will hold a two dimensional array of the long double data type. Have the user specify the number of rows and the number of columns for the two dimensional array. Have the user enter the values for each row and column element in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT