Suppose you have a file credits.txt that has lines with student last name and of
ID: 3836159 • Letter: S
Question
Suppose you have a file credits.txt that has lines with student last name and of credits earned as follows (HERE ARE ONLY THE FIRST 4 LINES, THERE ARE MANY MORE IN THE FILE!) Feldman 110 Frendel 55 Green 90 Lu 23 The first line means that Feldman so far has 110 earned credits at CSI. The second line means that Green has 90 credits so far. If someone has 90 credits or above it means he/she is a senior. WE DO NOT KNOW HOW MANY LINES THERE ARE IN THE FILE. Write the C++ code that (reads each line from the file and) prints out the names of all seniors and their credits. It also prints how many Seniors are listed in the file, and the average number of credits that the seniors have. So if the file was just the four lines above (OF COURSE IT HAS MORE), the output would be: Name Credits Feldman 110 Green 90 Total Seniors: 2 Average Senior credits: 100 Help with opening file: Sample code: ifstream inFile; inFile.open ("credits.txt");Explanation / Answer
Following is the C++ code for the above question.
=============================================
Test1.cpp
========
#include <iostream>
#include <fstream>
#define MAX 50
using namespace std;
int main(int argc, char *argv[]) {
ifstream in("credits.txt");
if(!in) {
cout << "Cannot open input file. ";
return 1;
}
char str[255];
int ctr1,ctr2,ctr3;
int Average = 0;
int count =0;
int Sum = 0;
char string2[MAX],string3[MAX];
while(in) {
in.getline(str, 255); // delim defaults to ' '
while(str[ctr1]!=' ')
{
string2[ctr1]=str[ctr1]; ++ctr1;
}
ctr3=0;
for(ctr2=ctr1+1; ctr2<strlen(str); ++ctr2)
{
string3[ctr3]=str[ctr2]; ++ctr3;
}
int Num = std::stoi(string3);
if(Num >= 90){
count++;
Sum = Sum+Num;
}
cout << string2 << " "<< Num << endl;
if(in) cout << str << endl;
}
Average = Sum/count;
cout<<count<<endl;
cout<<Average<<endl;
in.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.