2017-02-11 80 views
6

我想從文本文件中讀取數字並將其存儲到數組中。 當我嘗試讀取數組中的數字時,輸出略微關閉。 這是我的代碼:數組打印不正確值

struct point{ 
    double x[7]; 
    double y[7]; 
}point; 

int main() 
{ 
    FILE *fp; 
    fp = fopen("data_2.txt", "r"); 
    struct point points; 
    int len = 8; 
    int i = 0; 
    int j = 0; 
    int k = 0; 
    double a = 0; 
    double b = 0; 
    double c = 0; 
    double total = 0; 
    int left=0; 
    int right=0; 
    int line = 0; 
    for (i=0;i<len;i++) 
    { 
     fscanf(fp, "%lf %lf", &points.x[i],&points.y[i]); 
    } 
    for(i = 0; i < len;i++) 
     printf("looking at point %.2f %.2f\n",points.x[i],points.y[i]); 

    return(0); 
} 

我使用測試文件包含以下數字

2.3 7.5 
    7.6 7.1 
    8.5 3.0 
    5.9 0.7 
    1.0 2.0 
    5.1 5.8 
    4.0 4.5 
    4.3 3.4 

輸出我得到的是這樣的:

looking at point 2.30 4.30 
looking at point 7.60 7.10 
looking at point 8.50 3.00 
looking at point 5.90 0.70 
looking at point 1.00 2.00 
looking at point 5.10 5.80 
looking at point 4.00 4.50 
looking at point 4.30 3.40 

它是什麼,我做錯誤?

+0

這很奇怪。嘗試關閉文件,一旦它的使用完成功能。 – Shravan40

+3

你有一個數組索引溢出。數組'x,y'在struct point中只能存儲7個數字,但是您正在嘗試寫入8.擴大數組大小將修復它。 –

+0

您應該查看[適當的C格式化](// prohackr112.tk/pcf)。 –

回答

7

問題是你的結構不夠大,無法存儲8個數字,它調用undefined behavior。你有double x[7],但你循環到8.

爲什麼你得到的具體行爲,我可以在這裏重現OS X,我不知道。但這對你來說是未定義的行爲。

3

更新你的結構是這樣的:

struct point{ 
    double x[8]; 
    double y[8]; 
}point; 

這將幫助你閱讀並正確顯示數據。 example-with-stdin