我正在做这个作业,我需要为每次迭代从文件中读取一行。
我得到了这个输入:
200 38
220 48
230 68
240 48
260 68
280 68
300 48
0 0
我需要的是使用 fscanf 读取前 2 个整数。
然后在下一个循环中我将读取接下来的 2 个整数,依此类推。
前任。我会读200 38
然后我将在下一个循环中读取 220 48 。
有人可以帮我解决这个问题吗?
#include <stdio.h>
int main() {
int rate, hours;
float pay;
// This program will compute the pay rate of a person based on the working hours.
FILE *inputFileptr;
FILE *outputFileptr;
inputFileptr = fopen("input.txt","rt");
outputFileptr = fopen("pays.txt","at");
do {
fscanf(inputFileptr,"%d %d", &rate, &hours);
if ( hours <= 40 ) {
pay = (hours * rate) / 100.00;
fprintf(outputFileptr,"Pay at %d centavos/hr for %d hours is %.2f pesos \n", rate, hours, pay);
}
else if ( hours <= 60 && hours > 40) {
pay = ((((hours - 40)* rate) * 1.5) + ( rate * 40)) / 100.00;
fprintf(outputFileptr,"Pay at %d centavos/hr for %d hours is %.2f pesos \n", rate, hours, pay);
}
else if ( hours < 60 ) {
pay = ((((hours - 60) * rate) * 2) + (((hours - 40)* rate) * 1.5) + (rate * 40));
fprintf(outputFileptr,"Pay at %d centavos/hr for %d hours is %.2f pesos \n", rate, hours, pay);
}
} while ( rate == 0 && hours == 0);
fclose(inputFileptr);
fclose(outputFileptr);
return 0;
}
最佳答案
while 循环中的表达式表示 while 循环将在 rate == 0 && hours == 0
时继续。是真的,显然你应该将其更改为 rate != 0 && hours != 0
,否则当读到第一行“200 38”时就会立即停止。
同时,您的 if 表达式 else if ( hours < 60 )
,应该是else if ( hours > 60 )
。
关于c - 使用 do while 循环读取 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323923/