Using C++ Write a program that will create a file on the main directory with R r
ID: 3792871 • Letter: U
Question
Using C++
Write a program that will create a file on the main directory with R records of the type:
Data { integer id; char gender; int credits; }
where id: 000 – 1000; gender: m, f; credits: 0 – 124;
The program will:
(a) Prompt the user for the number of records to be created: R = [20 – 60]
(b) Generate random values for R records of the type Data above.
(c) Create a file and save these records in the file data.bin then close the file.
(d) Reopen the file, read the records and compute the average number of credits.
(e) Print a message to the screen showing the average number of credits for the students.
Note: 1. The program must close the file after it’s created and then after it’s been used. 2.
It is ok to have multiple id codes. Do not remove duplicate id numbers.
The output will look like this:
The file data.bin processed # records and the average number of credits is # Test your program with TWO values of R: 23, 57
Explanation / Answer
#include <fstream>
#include <vector>
#include <iostream>
#include <ostream>
#include <cstdlib>
#include <random>
#include <sstream>
enum gender{
male = 0,
female = 1
};
struct Data{
int id;
gender g;
int credits;
friend std::istream& operator>>(std::istream& is, Data& d){
std::string line;
std::getline(is, line);
std::stringstream strm(line);
std::string sid;
int m;
int credits;
strm >> sid;
int rpos = -1;
for(rpos = -1; rpos < (int)sid.size(); ++rpos){
if(sid[rpos]!='0') break;
}
if(rpos!=-1){
sid = sid.substr(rpos+1);
}
int id;
id = std::stoi(sid);
strm >> m;
strm >> credits;
d.id = id;
d.g = m == 0 ? male : female;
d.credits = credits;
return is;
}
friend std::ostream& operator<<(std::ostream& os, Data d){
auto sid = std::to_string(d.id);
if(sid.size() < 3){
sid = std::string(3-sid.size(),'0') + sid;
}
os << sid << " " << d.g << " " << d.credits << std::endl;
return os;
}
};
void createCreditTable(){
int R;
std::cout << "R:";
std::cin >> R;
if((R < 20) || (R > 60)){
std::cerr << "R should be in range [20-60]" << std::endl;
return;
}
std::vector<Data> D(R,Data());
//D.reserve(R);
std::ofstream ofs("data.bin");
std::uniform_int_distribution<int> di(0,1000);
std::default_random_engine g1;
std::uniform_int_distribution<int> dg(0,1);
std::default_random_engine g2;
std::uniform_int_distribution<int> dc(0,124);
std::default_random_engine g3;
for(int i = 0; i < R; ++i){
int ID = di(g1);
int g = dg(g2);
int cr = dc(g3);
auto& d = D[i];
d.id = ID;
d.g = g == 0 ? male : female;
d.credits = cr;
ofs << d;
}
ofs.close();
std::ifstream ifs("data.bin");
double s = 0;
for(int i = 0; i < R; ++i){
Data d;
ifs >> d;
s += d.credits;
}
std::cout << "Average Credit : " << s/R << std::endl;
}
int main(){
createCreditTable();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.