2015-10-26 41 views
2

我想读取一个.dat文件,其第一行包含一个浮点数,并且所有连续行都是“int * int”或“int/int”,并打印或返回浮点数是否为导致每个划分或乘法。 我非常不满意我得到的结果。我的经验仅限于C几个小时。因此,我不知道该程序缺少什么代码来执行代码的外观。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

非常感谢!我通过在main函数中首先计算行数然后使用rewind(fPointer)来修复它,然后继续从第一行获取浮点数。 –

回答

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获取一些有用的提示。

+0

@ user3121023。对。我错过了。 –

+0

谢谢,显然我忽略了strcmp的工作原理。 –

+0

注意:从OP的文章中不清楚是否需要'1.0 *'。对于'(1.0 * frstInt * scndInt)'来处理溢出也可能有类似的说法。示例OP数据和期望将有所帮助 – chux

相关问题