In: Computer Science
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct Student
{
int id;
string name;
float score;
};
void readData(Student students[10],int& size,string
fileName)
{
ifstream fin;
fin.open(fileName);
if (!fin.is_open())
return;
int si = 0;
while (!fin.eof())
{
string name;
getline(fin, name);
string line;
getline(fin, line);
stringstream ss(line);
int id;
float score;
ss >> id;
ss >> score;
Student s;
s.name = name;
s.id = id;
s.score = score;
students[si++] = s;
}
size = si;
}
float calculateTotalScore(Student stu[],int& size)
{
float sum = 0.0;
for (int i= 0;i<size;i++)
{
sum += stu[i].score;
}
return sum;
}
Student searchStudent(Student stu[],int size,string
name,float& totalScore)
{
Student s;
for (int i = 0;i < size;i++)
{
if(stu[i].name.find(name) !=
string::npos)
{
totalScore +=
stu[i].score;
s =
stu[i];
break;
}
}
return s;
}
void printtoFile(ofstream& fout,Student s)
{
fout << s.id << " " << s.name
<< " " << s.score<<"\n";
}
int main()
{
Student s[10];
int size;
string inFile, outFile;
cout<<"\ntype input file name : ";
cin >> inFile;
cout << "\ntype output file name : ";
cin >> outFile;
cout << "\n";
readData(s, size,inFile);
calculateTotalScore(s, size);
ofstream fout(outFile);
fout << "ID Name Score\n";
fout <<
"------------------------------\n";
for (int i = 0;i < size;i++)
{
printtoFile(fout, s[i]);
}
string str;
float totalScore = 0.0;
do
{
cout << "\n\ntype
student’s name you are searching for (type done to exit) :";
cin >> str;
printtoFile(fout,searchStudent(s,
size, str, totalScore));
} while (str != "done");
fout << "\nTotal Score : " << totalScore;
return 0;
}