In: Computer Science
Using the four step (viz., analyze the problem, develop a solution, code the solution, test the program) program development method, 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. BONUS POINTS will be awarded for input data validation and/or exception handling by “try-throw-catch” construct.
SOLUTION: STEP 1: Analyze the Problem - The problem requires user data entries via “for” loop to be saved in “employee.txt” file.
STEP 2: Develop a Solution - Open the file for dummy “read” (ifstream inFile). If the file exists, will ask the user if overwrite is allowed. If no, close the inFile and exit. If yes, close the inFile and open the file for write (ofstream outFile). Query user for data entry, display on console debug window, and write to the outFile. Close the outFile. After running the program, display the contents of the “employee.txt” file.
STEP 3: Code the Solution
Copy and paste your Visual Studio C++ code here:
STEP 4: Test and Correct the Program
Copy and Paste the display on your Console Debug window here:
PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU
#include <iostream>
#include <string>
#include <ctime>
#include <math.h>
#include <fstream>
using namespace std;
int main()
{
try
{
ifstream inFile;
inFile.open("employee.txt");
if (inFile)
{
cout << "This file already exists.Would you like to overwrite (Y/N) ";
char overwrite;
cin >> overwrite;
if (overwrite == 'Y' || overwrite == 'y')
{
inFile.close();
ofstream outfile;
outfile.open("employee.txt");
cout << "Please enter all 5 employee id sex(M/F) Hourly wage Years with company one by one\n";
for (int i = 0; i < 5; i++)
{
string id;
int year;
int hourly;
char sex;
cin >> id >> sex >> hourly >> year;
outfile << id << " " << sex << " " << hourly << " " << year << "\n";
}
outfile.close();
}
else
return 0;
}
else
{
inFile.close();
ofstream outfile;
outfile.open("employee.txt");
cout << "Please enter all 5 employee id sex(M/F) Hourly wage Years with company one by one\n";
for (int i = 0; i < 5; i++)
{
string id;
int year;
int hourly;
char sex;
cin >> id >> sex >> hourly >> year;
outfile << id << " " << sex << " " << hourly << " " << year;
}
outfile.close();
}
}
catch (std::ifstream::failure e)
{
std::cerr << "Exception opening/reading/closing file\n";
}
}