I am taking a C++ class and I am trying to create a function that returns char and double date types. I have the program running fine without the function. It reads data from a file (employee id, fname, lname, hours worked, hourly rate), calculates gross pay, taxes, netpay, ot pay, etc and prints it to the screen. I included the peice of code I want in the function below. I also included the working code.
Any help would be greatly appreciated!
Regards,
Joel
I need the function the perform the following:
======================================
ifstream fin ("employee.txt");
while (fin>>empid[counter]>>fname[counter]>>lastname[counter]>>hw[counter]>>hr[counter])
======================================
My program has a few other functions that are working fine but they olny return a single data type.
i.e.
======================================
int regHours (int totalhours){
int regularhours;
if(totalhours>40) regularhours=40;
else regularhours=totalhours;
return (regularhours);}
--------------------------------------
rh[i] = regHours (hw[i]);
======================================
My text file contains the following data which I am able to read fine and using the program without the function:
I am reading this data from the file and putting it into an array. The first three columns are char data types, the last two are double.
I tried to do the following in a few different variations but I am stuck.I searched the forum, and the tutorials and found info on templates that might work but I am having trouble interpreting from how it is used in the examples to how I need to use it.
Short answer: No. A function can return only one value.
Long answer:
You can pass multiple values back to the parent function in a few different ways.
1. Create a data container (struct/class) containing the values you want to return. Then just update your function to return the class type rather than void and change your return value to return the class. This way you will be able to return all the data, but still only return one item.
2. Use pointers. Keep your function returning void, and don't return any value. Just use "return;" Instead in your function arguments, include pointers to whatever you want to 'return'. Define a variable or pointer in the parent function and pass the address or value when you call the child function. This will allow the child function to change the actual variable defined in the parent function, but it will not have to return it because it modifies the original variable rather than a copy of it.
I prefer the second method, and use it quite frequently because it allows you to use the return value for something more informational, such as an int or bool defining the success/failure of the function and possible pass an error code back to the parent function.