Simple C Getting an input file and doing calculations Input
Simple C++: Getting an input file and doing calculations.
Input file to be read from should be named \"1030Prob1.dat\"::
Solution
//Program code begins
#include <stdio.h>
#include <stdlib.h> // For exit() function
#include <string.h>
int main()
{
FILE *fp;
char fn[100],b[100];
int c;
float d;
char fname[100],lname[100];
int id;
float salary,maxsalary=0;
if ((fp = fopen(\"1030Prob1.dat\", \"r\")) == NULL)
{
printf(\"Error! opening file\");
// Program exits if file pointer returns NULL.
exit(1);
}
else
{
while(1)
{
fscanf(fp,\"%s %s %d %f\",&a,&b,&c,&d); //read each line with formating(string,string,int,flaot) like fname,laname,id,salary
if(maxsalary<d) // findign max salary by comparing with previous max
{
maxsalary=d;
strcpy(fname,a);
strcpy(lname,b);
id=c;
}
if (feof(fp)) //close file to read when reaches to end
break;
}
printf(\"Max Salary \\t Fname \\t Lname \\t ID \ \"); //display outputs
printf(\"%f \\t %s \\t %s \\t %d \ \",maxsalary,fname,lname,id); //display outputs
}
return 0;
}
Input :
John Harris 11374 50000.00
Lisa Smith 11985 75000.00
Adam Johnson 12585 68500.00
Sheila Smith 11654 150000.00
Tristen Major 11274 75800.00
Yannic Lennart 15687 58000.00
Lorena Emil 17414 43000.00
Tereza Santeri 12597 48000.00
Output :
Max Salary Fname Lname ID
150000.000000 Sheila Smith 11654

