In: Computer Science
Please find below the code, code screenshots and output screenshots. Please refer to the screenshot of the code to understand the indentation of the code. Please get back to me if you need any change in code. Else please upvote
CODE:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
//function prototype
void printheading();
bool check_university_rating(int rating, int threshold);
void printUniversity(string university, int rating, string city, string state);
//main function
int main()
{
ifstream infile; //input file stream object
string filename; //Variable to store filename
int threshold; //Variable to store threshold value
string university; //Variable to store university name
string state; //Variable to store university state
string city; //Variable to store university city
int rating; //Variable to store rating
// Prompt the user for the name of the input file to open
cout << "Enter the name of the input file to open: ";
cin >> filename;
// Prompt the user for the rating threshold
cout << "Enter the rating threshold: ";
cin >> threshold;
//Open the file and take in the input from the file
infile.open(filename, ios::in); //Open the file in read mode
if(!infile) { //checking if file exists
cout<<"File input.txt does not exist\n"; //display error if file not exists
exit(1);
}
//Using a user defined function to output a heading to the terminal
printheading();
while(infile.eof() == 0) //loop until end of file in input file
{
infile >> university; //Reading the university from file
infile >> rating; //Reading the rating from file
infile >> city; //Reading the city from file
infile >> state; //Reading the state
//Using a user defined function to check if a university should be printed
if(check_university_rating(rating, threshold))
//Using a user defined function to output the appropriate universities
printUniversity(university, rating, city, state);
}
infile.close(); //closing the input file
return 0;
}
//user defined function to output a heading to the terminal
void printheading(){
cout << setw(15) << left << " University" <<" " <<setw(15) << left << " Rating" <<" ";
cout << setw(15) << left << " City" <<" "<< setw(15) << left <<" State";
cout <<"\n--------------- --------------- --------------- ---------------\n";
}
//user defined function to check if a university should be printed
bool check_university_rating(int rating, int threshold){
if(rating >= threshold)
return true; //return true if the rating is greater than or equal to the threshold
else
return false; //else return false
}
//user defined function to output the appropriate universities
void printUniversity(string university, int rating, string city, string state){
cout << setw(20) << left << university <<" " << setw(15) << left << rating <<" ";
cout << setw(15) << left << city <<" " << setw(15) << left << state <<"\n";
}
INPUT FILE:
OUTPUT: