In: Computer Science
write a C++ program that permits users to enter the following
information about your small company’s 5 employees and then writes
the information to a file “employee.txt”:
ID No. Sex (M/F) Hourly Wage Years with the
Company
Make sure that you open the file for write using the two-step
process of “trial read followed by write” so that an existing file
with the same name does not get inadvertently clobbered.
Close all open files after completing read or write
operations.
Test your program thoroughly. Using WordPad or Notepad, print out
the content of the created file “employee.txt” residing in your
project folder
CODE:
#include<iostream>
#include<fstream>
using namespace std;
//main method
int main(){
//two files
fstream fileTest, file;
//opening the TestFile to check whether there already exists such a
file
fileTest.open("employee.txt",ios::in);
if(fileTest == NULL){
//if it doesn't
fileTest.close();
//new file is created
file.open("employee.txt",ios::out);
cout<<"File Created"<<endl;
//asks the use the data of 5 employees
for(int i=0;i<5;i++){
//asking the Id, sex, wager, years
cout<<"Enter the ID number: ";
string id;
cin>>id;
cout<<"Enter Sex(M/F): ";
string sex;
cin>>sex;
cout<<"Enter the hourly wage: ";
double wager;
cin>>wager;
cout<<"Enter the number of years worked with the company:
";
int years;
cin>>years;
//printing the details to the file
file<<"ID No: "<<id<<" Sex: "<<sex<<"
Hourly wage: $"<<wager<<"/hour Years worked with the
company: "<<years<<" years"<<endl;
}
file.close();
}else{
//if the fileTest is not null the code exits
cout<<"File already exists!"<<endl;
}
return 0;
}
_____________________________________
CODE IMAGES:
______________________________________________
OUTPUT:
employee.txt
___________________________________________
Feel free to ask any questions in the comments section
Thank You!