簡體   English   中英

在c中將矩陣文本文件讀入數組

[英]Reading a matrix text file into a array in c

我已經開始學習用C語言編寫代碼了,我陷入了一個我應該讀取文件,將內容放在矩陣中,最后打印矩陣的任務。

輸入文件包含:

    ------01-1
    1--------1
    --0-1-----
    ----0-----
    ------0--1
    -----1--1-
    ------0--0
    0---------
    --11-----1
    0-1-----0-

這是我到目前為止編寫的代碼:

int main()
{   
    FILE *filename = fopen("file.txt","r");
    int matrix[10][10];
    int c;

    for(int i =0; i < 10; i++)
    {
        for(int j=0; j<10; j++)
        {
            c = fgetc(filename);
            if(c == '1')
            {
                matrix[i][j] = 1;
            }
            else if(c == '0')
            {
                matrix[i][j] = 0;
            }
        }
    }

    for(int a = 0; a < 10; a++)
    {
        for(int  b = 0; b < 10; b++)
        {
            printf("%d", matrix[a][b]);
        }
        printf("\n");
    }

}

輸出:

-520092443803-520092443-12480181
2686620131463841127199806539638031616085
1316435226866683164344001-520092443011
51119868016113146336314633624404833019927382943080192
26869241998418816-1123324798-2268660019980688424308334426866161992765860
0019927658711830833442686648199276586030801920
1-8756571168119980461561998099927-13626866284
0175821461101992769785308335604200816026866681992735205
199343520826867321992749998819927700401992769850-875656752419907241990720
11268674426869241992847904-1121896548-2119927710210

Press any key to continue.

我對輸出的猜測是,它不會將c值添加到矩陣中。 因此它打印出一個“空”數組; 空數組會導致數字怪異?

我知道我正在從文本文件中讀取字符。 所以我需要將它們轉換為int值。

但是,為什么我的代碼出錯了,哪里出錯了?

初始化矩陣

int matrix[10][10] = {0};

處理0和1以外的輸入

我們還需要處理什么:

  1. 連字符或-輸入:保存其他一些數字,例如:2或-1
  2. EOF或文件結尾:結束程序或類似處理
  3. 新行,尾隨空格或其他未知字符:忽略該字符並再次閱讀
c = fgetc(filename);
if(c == '1')
{
   matrix[i][j] = 1;
}
else if(c == '0')
{
    matrix[i][j] = 0;
}
else if(c == '-')
{
    matrix[i][j] = -1;  /* Special number for - */
}
else if(c == EOF)
{
    return -1; /* End of file handling */
}
else
{
   --j; /* Ignore this character and enter into loop again */
   /* Although modifying loop controlling var inside is not a good habit */
   /* For this small module, it should be fine */
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM