Question

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. 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. Then 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.

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.

A pointer parameter that points to a NutritionData.

A parameter for the number of NutritionData.

Parameters should be in camelCase. The function returns true or 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.

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.

- For the function that can retrieve a nutrition data.

The function should have the following parameters:

A parameter for the file name.

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 or 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.

Access the desired record from the file. The program should use the seek mechanism to access the desired record.

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.

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

CODE :
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
using namespace std;

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

//write a single record to file in binary mode
void writeToFile(ofstream &out, const char *name, double size, double carbCal, double fatCal, double protCal)
{
NutritionData n;
strcpy(n.foodName, name);
n.servingSize = size;
n.calFromCarb = carbCal;
n.calFromFat = fatCal;
n.calFromProtein = protCal;
n.totalCalories = n.calFromCarb + n.calFromFat + n.calFromProtein;
out.write((char *)&n, sizeof(n));
}

int main()
{
const char filename[] = "nutri.dat";
ofstream out(filename, ios::binary);


//write the records to file
writeToFile(out, "Apples raw", 110, 50.6, 1.2, 1.0);
writeToFile(out, "Bananas", 225, 186, 6.2, 8.2);
writeToFile(out, "Bread pita whole wheat", 64, 134, 14, 22.6);
writeToFile(out, "Broccoli raw", 91, 21.9, 2.8, 6.3);
writeToFile(out, "Carrots raw", 128, 46.6, 2.6, 3.3);

out.close();

//open the file
ifstream in(filename, ios::binary);
in.seekg( 2 * sizeof(NutritionData)); //go to the end of 2nd record i.e where 3rd record begins
NutritionData n;
in.read((char *) &n, sizeof(n));
in.close();
cout << "Food Name: " << n.foodName << endl;
cout << "Serving Size: " << n.servingSize << endl;
cout << "Calories Per Serving: " << n.totalCalories << endl;
cout << "Cals From Carb: " << n.calFromCarb << endl;
cout << "Cals From Fat: " << n.calFromFat << endl;
cout << "Cals From Protein: " << n.calFromProtein << endl;

}

Add a comment
Know the answer?
Add Answer to:
c++ program Notes 1. Your program should use named string constant for the file name to open the file. Do not add any pa...
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
  • 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...

  • 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...

  • 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++ program8. Array/File Functions Write a function named arrayToFile. The function should accept three arguments:...

    c++ program8. Array/File Functions Write a function named arrayToFile. The function should accept three arguments: the name of a file, a pointer to an int array, and the size of the array. The function should open the specified file in binary mode, write the contents of the array to the file, and then close the file. Write another function named fileToArray. This function should accept three argu- ments: the name of a file, a pointer to an int array, and the size...

  • 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...

  • 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...

  • (c programming): write a program that contains a function named getName, that does not get any...

    (c programming): write a program that contains a function named getName, that does not get any parameter and returns a character array of a random name from a constant list of 30 names, in a global array. the function returns that random name. each name in the list is a character string that consists of not more than 20 characters(not including finishing 0). the name consists of only characters from the american alphabet (a-zA-Z) and does not contain any "white"...

  • need help on C++ Discussion: The program should utilize 3 files. player.txt – Player name data...

    need help on C++ Discussion: The program should utilize 3 files. player.txt – Player name data file – It has: player ID, player first name, middle initial, last name soccer.txt – Player information file – It has: player ID, goals scored, number of penalties, jersey number output file - formatted according to the example provided later in this assignment a) Define a struct to hold the information for a person storing first name, middle initial, and   last name). b) Define...

  • 1. Create a file that contains 3 rows of data of the form: First Name Middle...

    1. Create a file that contains 3 rows of data of the form: First Name Middle Name Last Name Month Day Year Month Day Year GPA. This file represents student data consisting of first name, middle name, last name, registration month, registration day, registration year, birth month, birth day, birth year, current gpa. ...or you may download the data file inPut.txt. inPut.txt reads:​​​​​​​ Tsia Brian Smith 9 1 2013 2 27 1994 4.0 Harper Willis Smith 9 2 2013 9...

  • Write a menu based program implementing the following functions: (0) Write a function called displayMenu that...

    Write a menu based program implementing the following functions: (0) Write a function called displayMenu that does not take any parameters, but returns an integer representing your user's menu choice. Your program's main function should only comprise of the following: a do/while loop with the displayMenu function call inside the loop body switch/case, or if/else if/ ... for handling the calls of the functions based on the menu choice selected in displayMenu. the do/while loop should always continue as long...

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