2013-09-22 75 views
0

我寫這段代碼來讀取一個txt文件到一個二維數組中,它的工作正常,但在我的輸入文本文件中我有一個8 * 8的矩陣輸出給我看, 37周的cols在二維數組解決方案中讀取txt文件

#include <stdio.h> 

int main() 
{ 
    int c, i, j, row, col, nl, cr; 

    row = col = nl = cr = 0; 

    FILE *fp = fopen("image.txt", "r"); 

    // Figure out how many rows and columns the text file has 
    while ((c = getc(fp)) != EOF) 
    { 
     if (c == '\n') 
      nl++; 
     if (c == '\r') 
      cr++; 

     col++; 

     if (c == '\n') 
      row++; 

     putchar(c); 
    } 

    col = (col - (nl + cr)); 
    col = (int) (col/row); 

    printf("\nnumber of rows is %d\n", row); 
    printf("number of columns is %d\n\n", col); 



    return 0; 
} 

我的正常輸入:

255 50 9 50 1 50 50 1 
50 255 50 50 50 50 50 50 
50 50 255 50 50 50 50 50 
8 50 50 255 50 50 50 50 
50 50 50 50 255 50 50 50 
50 50 50 50 50 255 50 50 
1 50 50 50 50 50 255 50 
2 50 50 50 50 50 50 255 

和輸出圖像爲:enter image description here 有人能幫助嗎?

+0

37 = 8 * 8 + 1 !!!!!!!噢,我的猜測 – Butterflay

回答

0

這很有趣,我得到 -

number of rows is 8 
number of columns is 29 

的問題是,由於使用的getc,你算的實際字符數在文本文件中,當你閱讀255例如,這是不是一個真正的單字符與該值,它是3個字符值50('2'),53('5')和53('5')。你也可以在這裏計算空格(這可能是爲什麼我得到了與你不同的結果)

你應該將它們讀爲整數(例如fscanf),或者根據可接受的分隔符(空格和在這種情況下,我認爲換行符),然後才能相應地提前計數。或者,您可以將文件壓縮爲二進制格式,並且不用空格和換行符來處理所有麻煩,每個字符一個字節。儘管如此,它們不會是可讀的。

另外請注意,您的代碼假設固定的列每行數,一定要把它總是如此