使用do while循环读取.txt文件

时间:2018-09-14 01:45:22

标签: c loops

我正在做这个作业,我需要为每次迭代从文件中读取一行。

我得到了以下输入:

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;
}

1 个答案:

答案 0 :(得分:0)

while循环中的表达式表示rate == 0 && hours == 0为true时,while循环将继续,显然您应将其更改为rate != 0 && hours != 0,否则它将在读取第一行后立即停止'200 38'。

同时,您的if表达式else if ( hours < 60 )应该是else if ( hours > 60 )

相关问题