Issue regarding functions returning a string - c++

The program for my class needs to return the average score, the high score with first and last name as well as the low score. I get an error for the functions that find the names for the high and low score and I'm not sure what the issue is.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
float highestVal(float highScore, float score);
float lowestVal(float lowScore, float score);
string highFirstFun(float highScore, float score, string firstNameHigh);
string highLastFun(float highScore, float score, string lastNameHigh);
string lowFirstFun(float lowScore, float score, string firstNameLow);
string lowLastFun(float lowScore, float score, string lastNameLow);
int main() {
ifstream inFile;
string fileName = "", firstName = "", lastName = "";
float score, average;
float highScore = 0;
float lowScore = 100;
float studentNum = 0;
float sum = 0;
int i;
string highFirst = "", highLast = "";
string lowFirst = "" , lowLast = "";
cout << "Please enter the input file name: ";
cin >> fileName;
inFile.open(fileName);
while (!inFile.is_open()) {
cout << "Sorry, the file did not open. \nTry again, or type \"cancel\" to quit: ";
cin >> fileName;
if (fileName == "cancel") {
cout << "Cancelling..." << endl;
break;
}
else {
inFile.open(fileName);
}
}
if (inFile.is_open()) {
cout << "The scores are as follows: \n";
while (!inFile.eof()) {
inFile >> firstName >> lastName >> score;
cout << firstName << " " << lastName << " scored " << score << endl;
sum += score;
studentNum++;
highScore = highestVal(highScore, score);
lowScore = lowestVal(lowScore, score);
highFirst = highFirstFun(highScore, score, firstName);
highLast = highLastFun(highScore, score, lastName);
lowFirst = lowFirstFun(highScore, score, firstName);
lowLast = lowLastFun(highScore, score, lastName);
}
average = (sum / studentNum);
cout << "There are " << studentNum << " students with an average grade of " << average << endl;
cout << "The high score was: " << highScore << " from " << highFirst << " " << highLast << endl;
cout << "The low score was: " << lowScore << " from " << lowFirst << " " << lowLast << endl;
inFile.close();
}
return 0;
}
float highestVal(float highScore, float score)
{
if (score > highScore) {
highScore = score;
}
return (highScore);
}
float lowestVal(float lowScore, float score)
{
if (score < lowScore) {
lowScore = score;
}
return (lowScore);
}
string highFirstFun(float highScore, float score, string firstNameHigh)
{
if (score > highScore) {
return (firstNameHigh);
}
}
string highLastFun(float highScore, float score, string lastNameHigh)
{
if (score > highScore) {
return (lastNameHigh);
}
}
string lowFirstFun(float lowScore, float score, string firstNameLow)
{
if (score < lowScore) {
return (firstNameLow);
}
}
string lowLastFun(float lowScore, float score, string lastNameLow)
{
if (score < lowScore) {
return (lastNameLow);
}
}
Here is the Text File that it is pulling from called "Scores.txt":
John Smith 99.0
Sarah Johnson 85.0
Jim Robinson 70.0
Mary Anderson 100.0
Michael Jackson 92.0
Any help would be much appreciated!

A function that has a return type must always return that type. The function
string highFirstFun(float highScore, float score, string firstNameHigh);
For example must always return a string when it is called. The issue is the definition of your function
string highFirstFun(float highScore, float score, string firstNameHigh)
{
if (score > highScore) {
return (firstNameHigh);
}
}
highFirstFun() Will only return a string if (and only if) score is higher than highScore. Well, what will happen if score is not higher than highScore? This will be a problem for the function because it's not designed to do anything if a condition like this happens, so the compiler will complain about it. This applies to all your functions. To make them work, you'll have to find a way to make them return a string is all scenarios.

Related

File I/O assignment [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am working on an assignment, and the instruction is below:
This fifth assignment will allow you to better explore the concept of File I/O within the C++ programming language.
For this assignment, you are going to read-in (using C++ File I/O) the contents of a text file (.txt) and calculate the letter grade for a given student based upon weighted averages and write this out to a text file (.txt). We will use the weights as outlined in the Syllabus for this course: Assignments: 50%, Participation: 10%, Midterm Exam: 20%, Final Exam: 20%. Your program should read-in the grade category and then each of the respective scores separated/delimited by a comma.
Once you have finished reading the contents of the file you will need to invoke a function, calculateLetterGrade, that has a return type of void and two parameters: one of type double with By-Value semantics and the other of type char with By-Reference semantics. Your program should then write this calculated grade to another user specified text file (.txt) before terminating. You are expected to check to ensure that each respective file opens and that you properly close your file(s). The output file should have a score of 85.8 and letter grade B
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
void calculateLetterGrade(double score, char &grade);
int main(){
std::string fileName("");
char grade;
double totalScore(0);
std::cout << "Welcome to the great Grade Calculator!" << std::endl;
std::cout << "Please enter the file you wish to open: ";
std::cin >> fileName;
// open file to read
std::ifstream file(fileName);
//display the file on the console
if(file.is_open())
{
std::cout << "Reading from file " << fileName << "...\n";
std::cout << "Here is your file " << std::endl;
while(std::getline(file, fileName))
{
std::cout << fileName << std::endl;
}
}
else
{
std::cout << "Unable to open file. " << std::endl;
}
// loop upto end of file
while(!file.eof())
{
// read type
std::string gradeCategory("");
file >> gradeCategory; //stream extraction
// assign the weight in each category
double weight(0);
if(gradeCategory == "Assignments")
{
weight = 0.5; //50%
}
else if(gradeCategory == "Participation")
{
weight = 0.1; //10%
}
else if(gradeCategory == "Midterm" || gradeCategory == "Final")
{
weight = 0.2; //20%
}
double total(0), count(0);
// read count of scores for type
file >> count;
// loop for count times
for(int i = 0; i < count; i++)
{
// read score and add to total
double score;
file >> score;
total = total+score;
}
// calculate average and add weighted score to totalScore
double average = total/count;
totalScore = totalScore+(average*weight);
}
// close file
file.close();
// call function to get grade
std::cout << "Calculating grades...\n";
calculateLetterGrade(totalScore,grade);
// read output filename and open it
std::cout << "Save To (Filename): ";
std::cin >> fileName;
std::ofstream fileForGrade(fileName);
// write score to file
fileForGrade << totalScore;
// write grade to file and then close file
fileForGrade << grade;
fileForGrade.close();
std::cout << "Score & Letter Grade written to file: " << fileName << std::endl;
std::cout << "Thank you for using my program, have a bless day!" << std::endl;
return 0;
}
// function to calculate grade by give score
void calculateLetterGrade(double score, char &grade){
// assign 'A' if score greater than or equal to 90
if(score>=90){
grade = 'A';
}
// assign 'B' if score greater than or equal to 80
else if(score>=80){
grade = 'B';
}
// assign 'C' if score greater than or equal to 70
else if(score>=70){
grade = 'C';
}
// assign 'D' if score greater than or equal to 60
else if(score>=60){
grade = 'D';
}
// assign 'F', means fail
else{
grade = 'F';
}
}
My code compiles, but the output file comes out to be 0 F. Can someone point out what I did wrong in the code?
UPDATE: here is my latest code:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
void calculateLetterGrade(double score, char &grade);
int main(){
std::string fileName("");
char grade;
double totalScore(0);
std::cout << "Welcome to the great Grade Calculator!" << std::endl;
std::cout << "Please enter the file you wish to open: ";
std::cin >> fileName;
// open file to read
std::ifstream file(fileName);
//display the file on the console
if(file.is_open())
{
std::cout << "Reading from file " << fileName << "...\n";
std::cout << "Here is your file " << std::endl;
std::string line;
while(std::getline(file, line))
{
std::cout << line << std::endl;
std::istringstream iss(line);
std::string gradeCategory;
iss >> gradeCategory;
// assign the weight in each category
double weight(0);
if(gradeCategory == "Assignments")
{
weight = 0.5; //50%
}
else if(gradeCategory == "Participation")
{
weight = 0.1; //10%
}
else if(gradeCategory == "Midterm" || gradeCategory == "Final")
{
weight = 0.2; //20%
}
double total(0);
int count(0);
// read count of scores for type
iss >> count;
// loop for count times
for(int i = 0; i < count; ++i)
{
// read score and add to total
double score;
iss >> score;
total += score;
}
// calculate average and add weighted score to totalScore
double average = total/count;
totalScore = totalScore+(average*weight);
}
}
else
{
std::cout << "Unable to open file. " << std::endl;
}
// close file
file.close();
// call function to get grade
std::cout << "Calculating grades...\n";
calculateLetterGrade(totalScore,grade);
// read output filename and open it
std::cout << "Save To (Filename): ";
std::cin >> fileName;
std::ofstream fileForGrade(fileName);
// write score to file
fileForGrade << totalScore;
// write grade to file and then close file
fileForGrade << " " << grade;
fileForGrade.close();
std::cout << "Score & Letter Grade written to file: " << fileName << std::endl;
std::cout << "Thank you for using my program, have a bless day!" << std::endl;
return 0;
}
// function to calculate grade by give score
void calculateLetterGrade(double score, char &grade){
// assign 'A' if score greater than or equal to 90
if(score>=90){
grade = 'A';
}
// assign 'B' if score greater than or equal to 80
else if(score>=80){
grade = 'B';
}
// assign 'C' if score greater than or equal to 70
else if(score>=70){
grade = 'C';
}
// assign 'D' if score greater than or equal to 60
else if(score>=60){
grade = 'D';
}
// assign 'F', means fail
else{
grade = 'F';
}
}
And here is my input file named grade.txt:
Assignments
75,86,90,80,95,100
Participation
90
Midterm
75
Final
90
After the 1st while loop reads all of the file, file's position is at the end of the file. You need to call file.seekg(0) to reset the position back to the beginning of the file before you can read the contents again in the 2nd while loop.
std::ifstream file(fileName);
...
while(std::getline(file, fileName))
{
std::cout << fileName << std::endl;
}
file.seekg(0); // <-- ADD THIS!
...
That being said, consider combining the 2 loops. You can use std::istringstream to parse each line that is read.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
...
std::ifstream file(fileName);
if (file.is_open())
{
...
std::string line;
while (std::getline(file, line))
{
std::cout << line << std::endl;
std::istringstream iss(line);
std::string gradeCategory;
iss >> gradeCategory;
...
int count = 0;
iss >> count;
double total = 0.0;
for (int i = 0; i < count; ++i)
{
double score;
iss >> score;
total += score;
}
...
}
}
else
{
std::cout << "Unable to open file. " << std::endl;
}
...
UPDATE: given that we can now see what you input file actually looks like, the code shown so far will not be able to read it correctly. You will have to make some additional logic changes to the reading loop, eg:
...
std::string line;
while (std::getline(file, line))
{
std::cout << line << std::endl;
// assign the weight in each category
std::string gradeCategory = line;
double weight = 0.0;
if (gradeCategory == "Assignments")
{
weight = 0.5; //50%
}
else if (gradeCategory == "Participation")
{
weight = 0.1; //10%
}
else if (gradeCategory == "Midterm" || gradeCategory == "Final")
{
weight = 0.2; //20%
}
// read scores and add to total
std::getline(file, line);
std::istringstream iss(line);
double score, total = 0.0;
int count = 0;
char comma;
while (iss >> score)
{
total += score;
++count;
iss >> comma;
}
if (count != 0)
{
// calculate average and add weighted score to totalScore
double average = total / count;
totalScore += (average * weight);
}
}
...
Demo

Trouble with arrays and structs from input file

I am working on this problem for a college course and I'm unsure why it isn't working. I thought I had everything setup correctly, but when I try running the program the file won't open on the first attempt at inputting the file name and when I input it again I get an "Exception Thrown" error in the "xmemory" part that I have no idea what any of it means.
The input file that the program is taking data from is just a text file with the following data:
201742 Sponge Bob 82.6
201701 Patrick Star 14.1
201753 Squidward Tentacles 85.43
201744 Sandy Squirrel 75.61
201700 Plankton Plank 100.0
The final output of the program should display the highest and lowest grade with the students first and last name, the average score, and the number of students tested. Any help would be much appreciated.
// Zane Richards
// Lab 10 Q2
// 4/6/2020
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>
using namespace std;
struct student {
int ID;
string firstName;
string lastName;
float grade;
};
void maxGradeFunc(struct student* s, int size)
{
float maxGrade = 0;
string firstName, lastName;
for (int i = 0; i < size; ++i)
{
if (s[i].grade > maxGrade)
{
maxGrade = s[i].grade;
firstName = s[i].firstName;
lastName = s[i].lastName;
}
}
cout << "Maximum grade is " << maxGrade << endl;
cout << "The name of the student with the grade is: " << firstName << " " << lastName << endl;
}
void minGradeFunc(struct student* s, int size)
{
float minGrade = 999;
string firstName, lastName;
for (int i = 0; i < size; ++i)
{
if (s[i].grade < minGrade)
{
minGrade = s[i].grade;
firstName = s[i].firstName;
lastName = s[i].lastName;
}
}
cout << "Maximum grade is " << minGrade << endl;
cout << "The name of the student with the grade is: " << firstName << " " << lastName << endl;
}
void avgGradeFunc(struct student* s, int size)
{
float sum = 0;
for (int i = 0; i < size; ++i)
{
sum += s[i].grade;
}
float avg = sum / size;
cout << "Avearge grade is " << avg << endl;
cout << "The total number of students are: " << sum << " students" << endl;
}
int main()
{
ifstream inFile;
string fileName = "";
struct student s[5];
int ID;
string firstName, lastName;
float grade;
int i = 0;
cout << "Please enter the input file name: "; //File is named "Student.txt"
cin >> fileName;
while (!inFile.is_open()) {
cout << "Sorry, the file did not open. \nTry again, or type \"cancel\" to quit: ";
cin >> fileName;
if (fileName == "cancel") {
cout << "Cancelling..." << endl;
break;
}
else {
inFile.open(fileName);
}
}
while (inFile.is_open()) {
inFile >> ID;
s[i].ID = ID;
inFile >> firstName;
s[i].firstName = firstName;
inFile >> lastName;
s[i].lastName = lastName;
inFile >> grade;
s[i].grade = grade;
i++;
}
maxGradeFunc(s, 5);
minGradeFunc(s, 5);
avgGradeFunc(s, 5);
return 0;
}
Here is the error code I'm getting: https://i.stack.imgur.com/i35Oq.png
Figured out the issue, deleted the code that allowed for multiple attempts, and changed it to just open the file and that fixed it. Thanks for the help everyone, much appreciated!

Display Student ID and highest score from an array

I am having issues figuring out how to properly display a student's ID, out of 10 students, along with the highest score. For examle, if student 4 had the highest score if would display said student's ID and their score. I would like to add the student's first and last name as well, if possible. My code is as follows:
// HW2.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
using namespace std;
double TestScore(double score);
struct studentType {
string studentFName;
string studentLName;
double testScore;
int studentID;
double highScore;
};
int main()
{
// # of students
studentType student[10];
// For loop to get user input for the 10 students
for (int i = 0; i < 10; i++) {
cout << "Student ID: ";
cin >> student[i].studentID;
cout << "Student First Name: ";
cin >> student[i].studentFName;
cout << "Student Last Name: ";
cin >> student[i].studentLName;
cout << "Student's Test Score: ";
cin >> student[i].testScore;
cout << endl;
//Calls TestScore function
student[i].testScore = TestScore(student[i].testScore);
}
//Displays student ID and score v code that I need help on
//cout <<student[i].studentID << " has the highest score, which is "<< TestScore;
}
double TestScore(double score)
{
double newScore = 0;
//Determines student with highest score
for (int n = 0; n < 10; n++) {
if (score > newScore)
{
newScore = score;
}
}
return newScore;
}
It needs to :
1) read the students’ data into the array.
2) find the highest test score.
3) print the names of the students having the highest test score.
Your TestScore function doesn't really do anything. I've modified your code to have a function which returns the index of the student with the best score. Using this index, you can then access that element of the array, and print out its details.
#include <iostream>
using namespace std;
struct studentType {
string studentFName;
string studentLName;
double testScore;
int studentID;
double highScore;
};
int getBestStudent( studentType student[10] );
int main() {
// # of students
studentType student[10];
// For loop to get user input for the 10 students
for ( int i = 0; i < 10; i++ ) {
cout << "Student ID: ";
cin >> student[i].studentID;
cout << "Student First Name: ";
cin >> student[i].studentFName;
cout << "Student Last Name: ";
cin >> student[i].studentLName;
cout << "Student's Test Score: ";
cin >> student[i].testScore;
cout << endl;
}
// Displays student ID and score v code that I need help on
int best = getBestStudent( student );
cout <<student[best].studentFName << " " << student[best].studentLName << " has the highest score, which is "<< student[best].testScore;
}
int getBestStudent( studentType student[10] ) {
int best = 0;
//Determines student with highest score
for ( int n = 1; n < 10; n++ ) {
if ( student[n].testScore > student[best].testScore ) {
best = n;
}
}
return best;
}```

C++ Polymorphism Employee Project

For class I have to adapt a program I wrote last week for polymorphism. Last week it used a specific set of information for the employees but now I have to make it work with polymorphism as well as read/write data from a file, I am completely lost with what I am supposed to be doing, If someone could even point me in the right direction it would be so much help. I can post my current .h and .cpp file for a look at what I have as well as the instructions of what I am supposed to be doing.
.h
#pragma once
#include <string>
using namespace std;
class Employee {
private:
int employeeNumber; // Employee's employee number
string employeeName; //Employee's name
string streetAddress; //Employee's street address
string phoneNumber; //Employee's phone number
double hourlyWage; //Employee's hourly wage
double hoursWorked; //Employee's hours worked
double netPay; //Net pay
double grossPay; //Gross pay
public:
Employee();
Employee(int, string, string, string, double, double);
int getEmployeeNumber();
void setEmployeeNumber(int);
string getEmployeeName();
void setEmployeeName(string);
string getStreetAddress();
void setStreetAddress(string);
string getPhoneNumber();
void setPhoneNumber(string);
double getHourlyWage();
void setHourlyWage(double);
double getHoursWorked();
void setHoursWorked(double);
double calcPay()
{
const int OVER = 40;
double federal = 0.20;
double state = 0.075;
double timeHalf = 1.5;
double grossPay;
double netPay;
if (getHoursWorked() < OVER)
{
grossPay = getHoursWorked() * getHourlyWage();
netPay = grossPay - (grossPay * federal) - (grossPay * state);
}
if (getHoursWorked() >= OVER)
{
grossPay = getHoursWorked() * ((getHourlyWage() * timeHalf));
netPay = grossPay - (grossPay * federal) - (grossPay * state);
}
return netPay;
}
};
.cpp
#include <iostream>
#include <string>
#include <fstream>
#include "Employee.h"
#include <iomanip>
using namespace std;
Employee::Employee()
{
employeeNumber = 0; // Employee's employee number
employeeName = ""; //Employee's name
streetAddress = ""; //Employee's street address
phoneNumber = ""; //Employee's phone number
hourlyWage = 0; //Employee's hourly wage
hoursWorked = 0;
grossPay = 0;
netPay = 0;
}
Employee::Employee(int empNum, string empName, string streetAddress,
string phoneNumber, double hourlyWage, double hoursWorked)
{
employeeNumber = empNum;
employeeName = empName;
this->streetAddress = streetAddress;
this->phoneNumber = phoneNumber;
this->hourlyWage = hourlyWage;
this->hoursWorked = hoursWorked;
grossPay = 0;
netPay = 0;
}
int Employee::getEmployeeNumber()
{
return employeeNumber;
}
void Employee::setEmployeeNumber(int empNum)
{
employeeNumber = empNum;
}
string Employee::getEmployeeName()
{
return employeeName;
}
void Employee::setEmployeeName(string empName)
{
employeeName = empName;
}
string Employee::getStreetAddress()
{
return streetAddress;
}
void Employee::setStreetAddress(string strtAddrs)
{
streetAddress = strtAddrs;
}
string Employee::getPhoneNumber()
{
return phoneNumber;
}
void Employee::setPhoneNumber(string phnNum)
{
phoneNumber = phnNum;
}
double Employee::getHourlyWage()
{
return hourlyWage;
}
void Employee::setHourlyWage(double hrWage)
{
hourlyWage = hrWage;
}
double Employee::getHoursWorked()
{
return hoursWorked;
}
void Employee::setHoursWorked(double hrWorked)
{
hoursWorked = hrWorked;
}
void printCheck(Employee ee)
{
cout << "\n\n--------------------- Fluff Shuffle Electronics -------------------------------- \n";
cout << " Pay to the order of " << ee.getEmployeeName() << "...........................$" << ee.calcPay();
cout << "\n\n United Bank of Eastern Orem \n";
cout << "------------------------------------------------------------------------------- \n";
cout << " Hours Worked: " << ee.getHoursWorked();
cout << "\n Hourly Wage: " << ee.getHourlyWage();
cout << endl << endl;
}//End of function
void read(ifstream &in)
{
Employee employees[10];
int counter = 0;
while (in.read((char *)&employees[counter++], sizeof(Employee)))
for (int i = 0; i<counter; i++)
{
printCheck(employees[i]);
}
in.close();
}
void write(ofstream &out)
{
Instantiate your employees here first, then call their functions.
Employee joe(37, "Joe Brown", "123 Main St.", "123-6788", 10.00,
45.00);
printCheck(joe);
Employee sam(21, "Sam Jones", "45 East State", "661-9000", 12.00,
30.00);
printCheck(sam);
Employee mary(15, "Mary Smith", "12 High Street", "401-8900", 15.00, 40.00);
printCheck(mary);
out.write((char *)(&joe), sizeof(Employee));
out.write((char *)(&sam), sizeof(Employee));
out.write((char *)(&mary), sizeof(Employee));
out.close();
}
//Main function
int main()
{
int choice;
string filename;
while (true)
{
cout << "\nThis program has two options:\n";
cout << "1 - Create a data file, or\n";
cout << "2 - Read data from a file and print paychecks\n";
cout << "\n Press any other key to quit..........\n";
cout << "Please enter <1> to create a file or <2> to print
checks: ";
cin >> choice;
if (choice == 1)
{
cout << "Enter the file name: ";
cin >> filename;
ofstream out(filename);
out.open(filename.c_str(), ios::binary);
write(out);
}
else if (choice == 2)
{
cout << "Enter the file name: ";
cin >> filename;
ifstream in(filename);
in.open(filename.c_str(), ios::binary);
read(in);
}
else break;
//Calls function to displays information
}
}//End of main
These are the instructions for the project.
This is the diagram it refers to
To start: create two classes derived from Employee:
class HourlyEmployee: public Employee
{
};
class SalariedEmployee: public Employee
{
}
and move members related to Hourly working from Employee to HourlyEmployee, then add members related to Salary to SalariedEmployee (WeeklySalary).
This way (removing attributes related to hourly working) you make Employee class more general that can be a base for other kind of employees to (SalariedEmployee).
When you derive HourlyEmployee or SalariedEmployee from Employee, you mean they are kind of Employee, so members that Employee has, they will inherit automatically.

Adding user input to a method and putting the results into a file (C++)

Any help would be appreciated. All I'm trying to do is ask for user input, do some calculations and print the results in a file. I thought that my code was correct but when I run my program, I get nothing. Here is my code. Not looking for an answer, just for any tips to lead me in the right direction. Thanks.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
class Employee{
private:
int id;
int job_class;
int years_service;
int Ed;
float salary;
public:
void getData(ifstream&);
void computation(int job_class, int years_service, int Ed);
void printout(ofstream&);
};
void Employee::getData(ifstream& infile){
infile >> id >> job_class >> years_service >> Ed;
}
void Employee::computation(int job_class, int years_service, int Ed){
int basePay = 800;
float jobresult, Yearresult, Edresult;
if(job_class == 1){
jobresult = .05;
}
if(job_class == 2){
jobresult = .10;
}
if(job_class == 3){
jobresult = .15;
}
if(years_service <= 10){
Yearresult =.05;
}
if(years_service > 10){
Yearresult = .05;
}
if(Ed == 1){
Edresult = .00;
}
if(Ed == 2){
Edresult = .05;
}
if(Ed == 3){
Edresult = .12;
}
if(Ed == 4){
Edresult = .20;
}
salary = basePay + jobresult + Yearresult + Edresult;
//cout << salary;
}
void Employee::printout(ofstream& outfile){
outfile << "ID: " << "Salary " << endl;
outfile << id << salary;
}
int main(){
Employee emp; //created an Employee object
string input;
int id;
int job_class;
int years_service;
int Ed;
int basepay = 800;
cout << "Enter id" << endl;
cin >> id;
cout << "Enter job_class" << endl;
cin >> job_class;
cout << "Enter years of service" << endl;
cin >> years_service;
cout << "Enter education" << endl;
cin >> Ed;
ifstream inFile;
ofstream outFile;
//getline(cin, input);
inFile.open("example.txt");
outFile.open("examplee.txt");
//inFile.open(input);
std::string r = std::to_string(id); //converted id to string
inFile.open(r);
getline(cin, r);
std::string s = std::to_string(years_service);
inFile.open(s);
getline(cin, s);
std::string t = std::to_string(years_service);
inFile.open(t);
getline(cin, t);
std::string u = std::to_string(Ed);
inFile.open(u);
getline(cin, u);
if(inFile.is_open()){
emp.getData(inFile);
inFile.close();
}
outFile.open(r);
if(outFile.is_open()){
emp.computation(job_class, years_service, Ed);
float sal = basepay + job_class + years_service + Ed;
outFile << "ID " << "Salary " << endl;
outFile << id << sal;
outFile.close();
return 0;
}
}
What exactly are you trying to do with things like this?
std::string r = std::to_string(id); //converted id to string
inFile.open(r); /*Opens a file whose name is <id> ???*/
getline(cin, r); /*Overwrites the contents of r and does nothing??? */
Your entire program is fairly confusing. My best guess as to the (main) problem is that you aren't writing anything to inFile at all. Those 12 lines after outFile.open("examplee.txt") seem like they are trying to accomplish the following:
inFile << id << ' ' << job_class << ' ' << years_service << ' ' << ED << '\n';
Also, although I'm guessing this is for debugging purposes, but many of your methods do nothing or are unused. For example, you use emp.computation(job_class, years, ED) but after that you don't use emp at all in any way. And the three lines after that seem to mimic the behavior of Employee::computation and Employee::printout.
I suggest you carefully consider the specific steps you're trying to take, then think about the purpose of methods like getline and fstream::open, and ask yourself "Does this accomplish the task I had in mind?". Because I'm really struggling to understand what you are trying to do when I read this code.