我能夠讓程序打開該文件,但我無法讀取該信息。它需要逐行運行數據,但它一直被我的「錯誤讀取數據」循環所捕獲。我怎樣才能解決這個問題?將.txt文件讀入C程序
#include <stdio.h>
#include <stdlib.h>
int getdata(FILE *data, int *empid, int *dept, float *paygr, int *exe, int *hours);
void calcdata(float paygr, int exe, int hours, float *pay, float *overpay, float *tpay);
void printdata(int empid, int dept, float paygr, int exe, int hours, float pay, float overpay, float tpay);
int main(void)
{
FILE *data;
int empid;
int dept;
float paygr;
int exe;
int hours;
float pay;
float overpay;
float tpay;
data = fopen("emp_data.txt", "r");
if (data == NULL)
{
printf("Could not open input file\a\n");
exit(101);
}
while (getdata(data, &empid, &dept, &paygr, &exe, &hours))
{
calcdata(paygr, exe, hours, &pay, &overpay, &tpay);
printdata(empid, dept, paygr, exe, hours, pay, overpay, tpay);
}
fclose(data);
return 0;
}
int getdata(FILE *data, int* empid, int* dept, float *paygr, int *exe, int *hours)
{
int ioResult;
ioResult = fscanf(data, "%d%d%f%d%d", empid, dept, paygr, exe, hours);
if (ioResult == EOF)
{
return 0;
}
else if (ioResult != 5)
{
printf("\aError reading data\n");
return 0;
}
else
{
return 1;
}
}
void calcdata(float paygr, int exe, int hours, float *pay, float *overpay, float *tpay)
{
int overhrs;
if (exe == 'N' && hours > 40)
{
overhrs = hours - 40;
*tpay = (paygr * (hours - overhrs)) + (overhrs * (paygr * 1.5));
*pay = (hours - overhrs) * paygr;
*overpay = (overhrs * (paygr * 1.5));
}
else
{
*tpay = hours * paygr;
*pay = hours * paygr;
*overpay = 0.0;
}
}
void printdata(int empid, int dept, float paygr, int exe, int hours, float pay, float overpay, float tpay)
{
printf("%d %d %2f %d %d %2f %2f %2f\n", empid, dept, paygr, exe, hours, pay, overpay, tpay);
}
下面是emp_data.txt
205 14 7.54 N 45
3498 64 17.98 Y 38
1328 38 25.75 Y 49
9054 76 10.43 N 42
213 64 8.29 N 47
659 14 7.52 N 41
5487 14 25.75 Y 52
4326 38 7.54 N 36
1267 76 8.29 N 40
@LPs:可能帶有嵌入空格;-) – chqrlie
顯示emp_data.txt文件。 – BLUEPIXY
'scanf'是錯誤的。你有指針傳遞函數:'fscanf(data,「%d%d%f%d%d」,&empid,&dept,&paygr,&exe,&hours);' - >'fscanf(data,「%d% d'f%d%d「,empid,dept,paygr,exe,小時);' – LPs