A user a file that contains the database of employees in the company. The file i
ID: 3808960 • Letter: A
Question
A user a file that contains the database of employees in the company. The file is in the following format. Write a program to read the text file, and the display the content of the file on the screen in the following form. Allocate 20 spaces for the last name and use right alignment. Allocate 15 spaces for the first name and use right alignment. Allocate 10 spaces for salary and use right alignment the salary must have two significant digits alter the decimal point. Compute the average salary of the employees in the company and display the average on the screen. Use the file "HW6Probl.dat" for this program.Explanation / Answer
CODE:
------------------------------------
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
int main () {
// variables declared here...
string line;
double totalSalary = 0;
int numLines = 0;
ifstream myfile ("HW6Prob1.dat");
if (myfile.is_open())
{
// till the end of file, read
while ( getline (myfile,line) )
{
// to spilt the line read from file, pass it to istringstream.
istringstream iss(line);
string fname,lname,salary;
iss >> fname;
iss >> lname;
iss >> salary;
cout << setw(20) << fname << "," << setw(15) << lname << ":" << setw(10) << salary << endl;
// convert the salary to double value.
// alias of size_t
std::string::size_type sz;
// sum up the total salary.
totalSalary += std::stod (salary,&sz);
// take the count of salary details.
numLines++;
}
myfile.close();
cout << "Average=" << (totalSalary/numLines) << endl;
}
else cout << "Unable to open file";
return 0;
}
HW6Prob1.dat
------------------------
Harris John 50000.34
Smith Lisa 75000.00
Johnson Adam 68500.00
OUTPUT:
I have taken only 3 entries in the input file as above... Please take the complete input file and check.
$ g++ filereadDisplay.cpp
$ ./a.out
Unable to open file[niranjan@localhost prgms]$ ./a.out
Harris, John: 50000.34
Smith, Lisa: 75000.00
Johnson, Adam: 68500.00
Average=64500.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.