2014-10-05 71 views
0

是的,所以我很難嘗試用多行數字讀取一個文件(每行有浮點數和整數)。我有一個.txt文件,從那裏我試圖掃描這些行,並確定第二個浮點數是否大於第一個浮點數,並根據結果做出決定。到目前爲止,它可行,但問題在於我無法到達第二或第三行,因爲程序剛剛在第一行之後停止。如何用C中的多行浮點數和整數讀取文件?

這裏的.txt文件的樣本:

9.64 6.30 3 
2.77 3.98 10 
5.63 4.20 5 
0.00 0.00 0 

*當scanf函數的所有值命中0,它打破了循環並停止該程序。另外,我不一定知道文件中有多少行,但我知道每行都會有兩個浮點數和一個整數(按該順序)。

現在用這些數字,我試圖比較浮點值來確定一些東西,然後使用整數和浮點數來計算答案,然後將其打印到單獨的.txt文件中。 (我順便看了一下getf()函數和數組,但是我幾乎是一個bigginer,所以我就這樣做了,米仍然對如何/在哪裏使用它們感到困惑)。

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

int main (void) 
{ 
    int amount, x; 
    float first, second, current_value, total_positive, total_negative; 
    FILE *fin = fopen("numbersin.txt", "r"); 
    FILE *fout = fopen("resultout.txt", "w"); 

    x=1; 
    amount=0; 
    total_positive=0; 
    total_negatve=0; 

    while(x=1) 
    { 
     fscanf(fin, "%f %f %d", &first, &second, &amount); 
     if((second-first) > 0) 
     { 
      current_value=amount*(first+second); 
      total_positive=total_positive+current_value; 
      fprintf(fout, "%0.2f %0.2f %d:increase = %0.2f, total increase = %0.2f", first, second, amount, current_value, total_positive); 
     } 
     else if((second-first) < 0) 
     { 
      current_value=amount*(first+second); 
      total_negative=total_negative+current_value; 
      fprintf(fout, "%0.2f %0.2f %d:decrease = %0.2f, total decrease = %0.2f", first, second, amount, current_value, total_negative); 
     } 
     else((first==0)&&(second==0)&&(amount==0)); 
     { 
      break; 
     } 
    } 

    fclose(fin); 
    fclose(fout); 
    system("notepad resultout.txt"); 
    system("pause"); 
    return 0; 
} 
+0

再次檢查循環條件,這是一個任務。此外,請閱讀['scanf'參考](http://en.cppreference.com/w/c/io/fscanf)以查看它返回的內容,並將其用於您的循環條件。 – 2014-10-05 19:54:15

+0

'while(x = 1)'?? (fscanf(「%f%f%d」,&first,&second,&amount)!= EOF)' – DOOM 2014-10-05 19:55:54

+0

@DOOM更好的辦法是'while(fscanf(...)== 3 )' – 2014-10-05 19:58:32

回答

0

爲了您while循環正常工作,你需要改變

else((first==0)&&(second==0)&&(qty==0)); 
    { 
     break; 
    } 

else if ((first==0)&&(second==0)&&(amount==0)) 
    { 
     break; 
    } 

你現在的樣子,break;總是每次迭代執行。

+0

這是應該讓它從文件讀取/打印多行?因爲即使有它,我仍然得到相同的結果... – Jetuas 2014-10-05 20:03:12

+0

您是否也在'else if'行的末尾刪除了分號? – downhillFromHere 2014-10-05 20:23:00

+0

Ohhhhhh好的,是的...它現在完全可行! :)感謝@downhillFromHere!是的,刪除分號改變了一切!它現在很好用! – Jetuas 2014-10-05 20:24:46

相關問題