I would really appreciate if someone helps me out with this C++ assignment... PA
ID: 3915994 • Letter: I
Question
I would really appreciate if someone helps me out with this C++ assignment...
PART 1 A. REQUIREMENT Open a blank Word document, answer the following questions
Question1: Write the code to do the following: -open the input file named as data.txt, -read one line from input file data.txt -display that line on the screen -close the file
Question2: Write the code to do the following: -read input from the keyboard by displaying the message on the screen to ask and read the following information: * name of student * student id * score1, score2, score3 -open output file studentGrade.txt to write -Write to the output file studentGrade.txt the following information: Name of student – student id – score1, score2, score3 – average For example: James Smith – 0097765 - 98.50, 87.00, 78.25 – 87.92 -close file.
Question 3: Write the code to do the following: -open the file input.txt that contains several lines -Open file input.txt to read -read a line then display on the screen -continue read and display on the screen all the lines until end of the file -Write: “End of the file input.txt” on the screen -close input.txt file.
Explanation / Answer
Here is the completed code for all 3 parts of this question. Comments are included, go through it, learn how things work and let me know if you have any doubts. Thanks
Code for Question 1:
//opening 'data.txt' file for reading
ifstream inFile("data.txt");
//defining a string variable
string line;
//reading a line from inFile to set line variable
getline(inFile,line);
//displaying read line
cout<<line<<endl;
//closing the file
inFile.close();
Code for Question 2:
//defining variables
string name;
string id;
double score1,score2,score3,average;
//reading name
cout<<"Enter student name: ";
getline(cin,name);
//reading id
cout<<"Enter id: ";
cin>>id;
//reading 3 scores
cout<<"Enter score1, score2 and score3: ";
cin>>score1;
cin>>score2;
cin>>score3;
//opening file for writing
ofstream outFile("studentGrade.txt");
//finding average
average=(score1+score2+score3)/3;
//writing the data to the file in required format
outFile<<name<<" - "<<id<<" - "<<score1<<","<<score2<<","<<score3<<" - ";
//setting fixed precision to 2, to format average into 2 decimal places
outFile<<fixed<<setprecision(2)<<average<<endl;
//closing the file
outFile.close();
Code for Question 3:
//opening 'input.txt' file for reading
ifstream inFile("input.txt");
//defining a string variable
string line;
//continuously reading lines from inFile till EOF
while(getline(inFile,line)){
//displaying line
cout<<line<<endl;
}
cout<<"End of the file input.txt"<<endl;
//closing the file
inFile.close();