Answer:
The code is implemented below on C++
Step-by-step explanation:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// function declaration
int PrintStudents(string inputFile, int min_score,string outputFile);
int split(string s,char sep, string words[], int max_words );
int main() {
// test the function
int n = PrintStudents("students.txt",80,"outStudents.txt");
if(n != -1)
cout<<"\\ No. of students : "<<n<<endl;
else
cout<<"\\ No such file exists";
return 0;
}
// function to write the details of the students whose score >= min_score
// inputs : input file, minimum score and output file
// output : number of records read, -1 if error
int PrintStudents(string inputFile, int min_score,string outputFile)
{ // open the input file
ifstream fin(inputFile.c_str());
// if input file can be opened
if(fin.is_open())
{ // open the output file for writing
ofstream fout(outputFile.c_str());
int n=0,score;
string line;
string words[3];
// read till the end of file
while(!fin.eof())
{
getline(fin,line);
n++;
// get the score from the record read
score = split(line,',',words,3);
// check if score>=min_score, then write to output file
if(score >= min_score)
fout<<words[0]<<", "<<words[2]<<"\\";
if(fin.eof())
break;
}
// close the files
fin.close();
fout.close();
return n; // return the number of records read
}else
{
fin.close();
return -1; // file not found
}
}
// function to split a string on a given separator and return the score
// inputs : string , word separator, array of words and max_words
// output is the score
int split(string s,char sep, string words[], int max_words )
{
int index=0,i=0 ;
//loop to extract the words from the line
while(s.find(sep,index+1)!= -1){
words[i] = s.substr(index,s.find(sep,index+1)-index);
i++;
index = s.find(sep,index+1)+2;
}
words[i] = s.substr(index); // extract the last word
// convert to integer and return the score
return(stoi(words[1]));
}