Question

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 program to process structured data stored in a 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)

servingSize (double)

calFromCarb (double)

calFromFat (double)

calFromProtein (double)

totalCalories (double)

Use the data types in parentheses for the fields.

Create File

Create a binary file named test.dat. The file name should be defined in a named string constant. The string constant identifier should be used every time the file name is needed in the program.

If the file already exists, print the message, "The file test.dat is an existing file. You can either delete the file or move it to another location and then run the program again." The program should terminate after printing out the message.

Write five records of structured data to the file in binary format. Each record of data contains these fields: food name, serving size in grams, calories from carb, calories from fat and calories from protein.

Use 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

Close the file.

Read Data From File

Open the file and access the third record from the file. The program should use the seek mechanism to access the desired record.

Read the third record.

Process the record by calculating the calories per serving.

Print the third record to the screen.

Close the file.

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

#include<iostream>
#include <fstream>
#include<string>
using namespace std;

//Defining Structure
struct NutritionData{
   string foodName;
   double servingSize,calFromCarb,calFromFat,calFromProtein,totalCalories;  
};

int main () {
// open a file in write mode.
ofstream filestream("test.dat");
if (filestream.is_open())
      {
       // write inputted data into the file.
        filestream << "Apples raw, 110, 50.6, 1.2, 1.0\n";
        filestream << "Bananas, 225, 186, 6.2, 8.2\n";
        filestream << "Bread pita whole wheat, 64, 134, 14, 22.6\n";
        filestream << "Broccoli raw, 91, 21.9, 2.8, 6.3\n";
        filestream << "Carrots raw, 128, 46.6, 2.6, 3.3\n";
        // close the opened file.
        filestream.close();
      }
// Error Case message display
else cout <<"File opening is fail.";


    // open a file in read mode.
   ifstream file("test.dat");
   //initializing string phonenum to store the input_string
   string stringline;
    string nutrionstring;
   //using std::getline to fetch a line from the file and process it:
   int count=0;
   while (std::getline(file, stringline)) {
      // Process strngline here
      count+=1;
      if(count==3){nutrionstring=stringline;}// get the line number 3

   }

   //parsing nutrionstring;
   string s1(nutrionstring);
   string s2(s1, 0, 22);
   string s3 = s1.substr(24,2);
   string s4 = s1.substr(28,3);
   string s5 = s1.substr(33,2);
   string s6 = s1.substr(37,4);
   //type casting values
   double temp =stod (s3);
   double temp1 =stod (s4);
   double temp2 =stod (s5);
   double temp3 =stod (s6);


  

    //assigning values to struct
   struct NutritionData nuc;
    nuc.foodName=s2;
    nuc.servingSize=temp;
    nuc.calFromCarb=temp1;
    nuc.calFromFat=temp2;
    nuc.calFromProtein=temp3;
//    nuc.totalCalories=;
    cout<<nuc.foodName<<endl;
    cout<<"Serving Size:"<<nuc.servingSize<<endl;
    cout<<"Calories From Carb:"<<nuc.calFromCarb<<endl;
    cout<<"Calories From Fat: "<<nuc.calFromFat<<endl;
    cout<<"Calories From Protein:"<<nuc.calFromProtein<<endl;

return 0;
}

Output:

Add a comment
Know the answer?
Add Answer to:
C++ 1. Your program should use named string constant for the file name to open the...
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....

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

  • Create a class named Module2. You should submit your source code file (Module2.java). The Module2 class...

    Create a class named Module2. You should submit your source code file (Module2.java). The Module2 class should contain the following data fields and methods (note that all data and methods are for objects unless specified as being for the entire class) Data fields: A String object named firstName A String object named middleName A String object name lastName Methods: A Module2 constructor method that accepts no parameters and initializes the data fields from 1) to empty Strings (e.g., firstName =...

  • C++ Write a function parseScores which takes a single input argument, a file name, as a string. Your function should read each line from the given filename, parse and process the data, and print the r...

    C++ Write a function parseScores which takes a single input argument, a file name, as a string. Your function should read each line from the given filename, parse and process the data, and print the required information. Your function should return the number of student entries read from the file. Empty lines do not count as entries, and should be ignored. If the input file cannot be opened, return -1 and do not print anything.     Your function should be named...

  • C++ Write a program that uses an arrays of at least 20 string . It should...

    C++ Write a program that uses an arrays of at least 20 string . It should call a function that uses the linear search algorithm to locate one of the name. Read list of name from an input file call "StudentName.txt" The function should keep a count of the numbers of comparisons it makes until it finds the value. The program then should call a function that uses the binary search algorithm to locate the same value. It should also...

  • please write in C++ Write a program that uses a structure to store the following inventory...

    please write in C++ Write a program that uses a structure to store the following inventory data in a file: The data can be either read from a text file or the keyboard Item name (string) Quantity on hand(int) Wholesale cost(double) Retail Cost(double) The program should have a menu that allows the user to perform the following tasks: Add new records to the file Display any record in the file User will provide the name of the item or the...

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

  • Write a program (C++) that shows Game sales. The program should use a structure to store...

    Write a program (C++) that shows Game sales. The program should use a structure to store the following data about the Game sale: Game company Type of Game (Action, Adventure, Sports etc.) Year of Sale Sale Price The program should use an array of at least 3 structures (3 variables of the same structure). It should let the user enter data into the array, change the contents of any element and display the data stored in the array. The program...

  • In C++ please. 7.26 LAB: Nutritional information (classes/constructors) Given main(), complete the Food Item class (in...

    In C++ please. 7.26 LAB: Nutritional information (classes/constructors) Given main(), complete the Food Item class (in files Foodltem.h and Fooditem.cpp) with constructors to initialize each food item. The default constructor should initialize the name to "None" and all other fields to 0.0. The second constructor should have four parameters (food name, grams of fat, grams of carbohydrates, and grams of protein) and should assign each private field with the appropriate parameter value. Ex: If the input is: M&M's 10.0 34.0...

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