我想讀取一個.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;
}
非常感謝!我通過在main函數中首先計算行數然後使用rewind(fPointer)來修復它,然後繼續從第一行獲取浮點數。 –