46.8k views
2 votes
Exercise 4: Bring in program grades.cpp and grades.txt from the Lab 10 folder. Fill in the code in bold so that the data is properly read from grades.txt. and the desired output to the screen is as follows: OUTPUT TO SCREEN DATAFILE Adara Starr has a(n) 94 average Adara Starr 94 David Starr has a(n) 91 average David Starr 91 Sophia Starr has a(n) 94 average Sophia Starr 94 Maria Starr has a(n) 91 average Maria Starr 91 Danielle DeFino has a(n) 94 average Danielle DeFino 94 Dominic DeFino has a(n) 98 average Dominic DeFino 98 McKenna DeFino has a(n) 92 average McKenna DeFino 92 Taylor McIntire has a(n) 99 average Taylor McIntire 99 Torrie McIntire has a(n) 91 average Torrie McIntire 91 Emily Garrett has a(n) 97 average Emily Garrett 97 Lauren Garrett has a(n) 92 average Lauren Garrett 92 Marlene Starr has a(n) 83 average Marlene Starr 83 Donald DeFino has a(n) 73 average Donald DeFino 73

1 Answer

1 vote

Answer:

Here is the C++ program:

#include <fstream> //to create, write and read a file

#include <iostream> // to use input output functions

using namespace std; //to access objects like cin cout

const int MAXNAME = 20; //MAXNAME is set to 20 as a constant

int main(){ //start of main() function

ifstream inData; //creates an object of ifstream class

inData.open("grades.txt"); //uses that object to access and opens the text file using open() method

char name[MAXNAME + 1]; // holds the names

float average; //stores the average

inData.get(name,MAXNAME+1); //Extracts names characters from the file and stores them as a c-string until MAXNAME+1 characters have been extracted

while (inData){ //iterates through the file

inData >> average; //reads averages from file using the stream extraction operator

cout << name << " has a(n) " << average << " average." << endl; //prints the names along with their averages

inData.ignore(50,'\\'); //ignores 50 characters and resumes when new line character is reached. It is used to clear characters from input buffer

inData.get(name,MAXNAME+1);} //keeps extracting names from file

return 0; }

Explanation:

The program is well explained in the comments added to each line of the code. The program uses fstream object inData to access the grades.txt file. It gets and extracts the contents of the file using get() method, reads and extracts averages from file using the stream extraction operator. Then program displays the names along with their averages from grades.txt on output screen.

The grades.txt file, program and its output is attached.

Exercise 4: Bring in program grades.cpp and grades.txt from the Lab 10 folder. Fill-example-1
Exercise 4: Bring in program grades.cpp and grades.txt from the Lab 10 folder. Fill-example-2
User Marcos Griselli
by
4.7k points