[英]Reading a .txt file using a do while loop
I'm doing this homework where I need to read a line from a file for each iteration.我正在做这个作业,我需要为每次迭代从文件中读取一行。
I got this inputs:我得到了这个输入:
200 38
220 48
230 68
240 48
260 68
280 68
300 48
0 0
What I need is to read the first 2 ints using fscanf.我需要的是使用 fscanf 读取前 2 个整数。
Then on the next loop I'll read the next 2 ints and so on.然后在下一个循环中,我将读取接下来的 2 个整数,依此类推。 Ex.
前任。 i'll read 200 38
我会读 200 38
then i'll read 220 48 on the next loop.然后我将在下一个循环中读取 220 48。
Can somebody help me with this?有人可以帮我解决这个问题吗?
#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;
}
The expression here in your while loop, means the while loop will continue when rate == 0 && hours == 0
is true, clearly you should change it to rate != 0 && hours != 0
, otherwise it will immediately stop soon as it reads the first line '200 38'. while 循环中的表达式表示 while 循环将在
rate == 0 && hours == 0
为真时继续,显然您应该将其更改为rate != 0 && hours != 0
,否则它将立即停止它读取第一行'200 38'。
Meanwhile, your if expression else if ( hours < 60 )
, it should be else if ( hours > 60 )
.同时,你的 if 表达式
else if ( hours < 60 )
,应该是else if ( hours > 60 )
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.