Reading a Second Variable from a file
Aug 1, 2012 at 5:36pm UTC
I'm trying to get information from a file and perform calculations with it, but the second float value is not reading properly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fullName;
float payRate, hoursWorked;
int regularHours = 35;
float grossPay, overtimePay, totalPay;
//Open data file Employee
ifstream Employeer("Employee.dat" );
//Header - 2 lines! Note that the width is 11 instead of 10
//to account for the '$' in the output.
cout << left << setw(18) << "Full" << setw(9) << "Hours" <<
setw(10) << "Pay" << setw(11) << "Gross" << setw(11)
<< "Overtime" << setw(11) << "Total" << endl;
cout << left << setw(18) << "Name" << setw(9) << "Worked" <<
setw(11) << "Rate" << setw(11) << "Pay" << setw(11)
<< "Pay" << setw(11) << "Pay" << endl;
//Read
getline(Employeer, fullName, '~' );
Employeer >> hoursWorked >> payRate;
//Calculations
grossPay = regularHours * payRate;
if (hoursWorked - regularHours > 0)
{
overtimePay = (hoursWorked - regularHours) * (payRate * 1.5);
}
else
{
overtimePay = 0;
}
totalPay = grossPay + overtimePay;
//Display
cout << left << setw(18) << fullName << setw(9) << hoursWorked << "$" << fixed
<< setprecision(2) << setw(10) << payRate << "$" << fixed << setprecision(2)
<< setw(10) << grossPay << "$" << fixed << setprecision(2) << setw(10)
<< overtimePay << "$" << fixed << setprecision(2) << setw(10)
<< totalPay << endl;
Employeer.close();
cin.get();
cin.ignore();
return 0;
}
When I try to run it all I get is
Full Hours Pay Gross Overtime Total
Name Worked Rate Pay Pay Pay
callaway 6 $488353612100771700000000000000000.00$170923767716976
45000000000000000000.00$0.00 $17092376771697645000000000000000000.00
Aug 1, 2012 at 5:48pm UTC
I'm taking a guess, '~'
is used as a delimiter throughout the file? If so, then you need to extract it between extracting hoursWorked and payRate.
It would help to see the formatting of the file.
Aug 1, 2012 at 5:50pm UTC
Yes, '~' is.
Here is the file:
callaway~6~40
hanson~6.5~48
goldberg~8~35
stallman~8.5~50
Aug 1, 2012 at 7:03pm UTC
The quick and dirty method is to declare a
char junk;
and extract that second '~' before payRate:
1 2
getline(Employeer, fullName, '~' );
Employeer >> hoursWorked >> junk >>payRate;
Though I wonder if that '\n' after "40" is going to make "hanson", "\nhanson". Might be wise to use cin.get() after extracting payRate.
A more flexible way to do this would be to extract the entire line as one string, and then use the delimiter to parse that.
Last edited on Aug 1, 2012 at 7:03pm UTC
Aug 1, 2012 at 8:07pm UTC
You might be interested in strtok()
from <cstring>
.
Topic archived. No new replies allowed.