Write a C++ program.
1) Write a program that writes the grades for 3 students.
Declare a variable of type ofstream which is used to output a stream into a file:
ofstream output; // output is the name of the variable
Prompt the user to input values for the grades of 3 students.
Use the output operator (<<) to write the grades into grades.txt:
output << grade1 << " " << grade2 << " " << grade3 << endl;
You may use IO manipulation commands (e.g. setw) in the above statement.
Close your file:
output.close();
After running the code, locate the grades.txt file on your computer. It must show the data you entered.
2) Write a second program reads the grades.
Declare a variable of type ifstream which is used to input a stream from a file:
ifstream input; // input is the name of the variable
Use the input operator (>>) to read data from the above file:
input >> score1 >> score2 << score3;
// the values in the file will be stored in the above variables
Use cout to display the above values.
Close your file:
input.close();
#include<iostream>
#include<fstream>
using namespace std;
//driver function
int main(){
//variable to output stream into file
ofstream output;
//three integer variables to input grades of students.
int grade1, grade2, grade3;
//open file with file name-grades.txt.
output.open("grades.txt");
//prompt user to enter the grades
cout<<"Enter the grades of three students: ";
//take input
cin>>grade1>>grade2>>grade3;
//write grades of students into file.
output<<grade1<<" "<<grade2<<"
"<<grade3<<endl;
//close the file.
output.close();
return 0;
}
#include<iostream>
#include<fstream>
using namespace std;
//driver function
int main(){
//variable to input stream from file
ifstream input;
//three integer variables to input grades of students.
int grade1, grade2, grade3;
//open file with file name-grades.txt.
input.open("grades.txt");
//read from file.
input>>grade1>>grade2>>grade3;
//print grades of students.
cout<<grade1<<" "<<grade2<<"
"<<grade3<<endl;
//close the file.
input.close();
return 0;
}
CODE1
CODE2
So if you have any doubt regarding this solution please feel free to ask in the comment section below and if it is helpful then please upvote the solution, THANK YOU.
Get Answers For Free
Most questions answered within 1 hours.