C读取文件行并打印它们

时间:2015-10-26 21:04:11

标签: c

我想读一个.dat文件,其第一行包含一个浮点数,所有连续行都是" int * int"或" int / int"并打印或返回浮点数是否为每次除法或乘法的结果。 我对我得到的结果非常不满意。我的经验仅限于几个小时做C.所以我不知道该程序缺少什么样做代码看起来会像它那样。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int countlines(FILE* f){
    int nLines = -1;
    char xLine[10];
    while(fgets(xLine,10,f)!=NULL){
        nLines+=1;
    }
    return nLines;
}

int main(){

    FILE * fPointer = fopen("test.dat", "r");

    float dpFloat;
    char oprnd[10];
    int frstInt;
    int scndInt;

    //get float from first line
    fscanf(fPointer, "%f", &dpFloat);

    //count amount of lines below float
    int amtLines = countlines(fPointer);

    //loop through the other lines and get 
    int i;
    for (i = 0; i < amtLines; i++){

        fscanf(fPointer, "%d %s %d", &frstInt, oprnd, &scndInt);

        //checking what has been read
        printf("%d. %d %s %d\n", i, frstInt, oprnd, scndInt);

        //print 1 if firstline float is quot/prod of consecutive line/s
        //else 0
        if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
        if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);

    }

    fclose(fPointer);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

问题1:strcmp在其参数相等时返回0,而不是1 问题2:frstInt/scndInt会截断结果。通过向表达式添加1.0*来修复它。

    if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
    if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);

需要

    if (strcmp(oprnd,"*") == 0) printf("%i\n", (frstInt*scndInt)==dpFloat);
    if (strcmp(oprnd,"/") == 0) printf("%i\n", (1.0*frstInt/scndInt)==dpFloat);
                       //   ^^^                 ^^^

请注意比较浮点数的缺陷。最好在公差范围内对它们进行比较。有关一些有用的提示,请参阅Comparing floating point numbers in C

相关问题