Hey, I was wondering how to have Fscanf loop and do multiple calculations for 4 different employee numbers with 4 different hours and 4 different pay rates.

#include <stdio.h>

double pay_calc (double hours_worked, double pay_rate) 
{
double tax,gross_pay,net_pay; 
gross_pay = hours_worked * pay_rate;
if (hours_worked > 40) 
gross_pay = hours_worked * (pay_rate *1.5) ;
tax = gross_pay * .03625;

net_pay = gross_pay - tax;
return net_pay;
}

int main()

{
FILE *input;
int employee_number;
double hours_worked, pay_rate;
input = fopen("pay_file.txt", "r");
fscanf (input, "%d", &employee_number);
/*printf ("Enter in hours worked: ");
scanf ("%lf", &hours_worked);*/ 
fscanf (input, "%lf", &hours_worked);

/*printf ("Enter in pay_rate: ");
scanf ("%lf", &pay_rate);*/
fscanf(input, "%lf", &pay_rate);
fclose(input);

printf ("%d's pay is %lf\n", employee_number,pay_calc(hours_worked, pay_rate));

return 0;

}

This is how I set up pay_file.txt

101
44
7.50
102
30
6.00
103
40
8.50
105
48
12.00

Thanks in advance for any help.

Recommended Answers

All 2 Replies

You have no formatting of the file beyond a whitespace separated sequence of values, so the loop is trivial:

while (fscanf(input, "%lf", &value) == 1) {
    /* Process the value */
}

fscanf will return the number of converted items, so if you're asking for one item and the return value isn't 1, either there's a read error (bad stream or invalid value) or you've reached end-of-file.

For multiple values in a record, you can typically assume that the first value in the record implies that the subsequent values exist. So it would become:

while (fscanf(input, "%lf", &first_value) == 1) {
    fscanf(input, "%lf", &second_value);
    fscanf(input, "%lf", &third_value);

    /* Process the value */
}

So thats how to do it! Thanks! I have the same problem in retrieving the account names and balances on my .dbf file using fscanf but no worries problem solved! Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.