2016-12-05 41 views
0

テキストファイルの数値を配列に読み込もうとしています。テキストファイルから数値リストを2次元配列に読み込む

11 10 23 3 23 98 39 12 9 10 
10 23 23 23 23 2 2 2 2 2 
…etc… 

マイコード:

#include <stdio.h> 
int main() 
{ 
    FILE *myFile; 
    myFile = fopen("snumbers.txt", "r"); 

    //read file into array 
    int numberArray[100][100]; 
    int i; 



} 

私はnumberArray[1][1]にアクセスした場合ので、私はそれを作るにはどうすればよいのテキストファイル、「snumbers.txtは」行あたり10個の数字と5行のすべてのスペースで区切られていそれは私に数字「23」を与えるだろう。

+2

2つのforループを使用して、2つ目のテストは最初のテストでテストします。 –

+0

入力データが確実にループを使用してアレイに読み込まれている場合。 for(){for(){}} –

+2

あなたのサンプル入力データは5x20クレームと結びついていないようです。あなたは、各行に10の数字を持つ2行の数字を表示します。実際のデータ形式は何ですか? 'fscanf()'を使って数値を読み取る際の問題は何ですか? –

答えて

0

ここでは、入力ファイルを配列に読み込む完全なコードを示します。私は文字を読んで数値に変換する 'コンバーター'を作成しました。あなたは数字の間にスペースが1つあると仮定します。これをそのまま使用することもできますし、この例を使っていくつかのソリューションを実装することもできます。

#include <stdio.h> 
#include <string.h> 

int main(void){ 
    FILE *myFile; // file pointer to read the input file 
    int i,  // helper var , use in the for loop 
     n,  // helper var, use to read chars and create numbers 
     arr[100][100] , // the 'big' array 
     row=0, // rows in the array 
     col, // columns in the array 
     zero=(int)'0'; // helper when converting chars to integers 
    char line[512]; // long enough to pickup one line in the input/text file 
    myFile=fopen("snumbers.txt","r"); 
    if (myFile){ 
     // input file have to have to format of number follow by one not-digit char (like space or comma) 
     while(fgets(line,512,myFile)){ 
       col = 0;  // reset column counter for each row 
       n = 0;   // will help in converting digits into decimal number 
       for(i=0;i<strlen(line);i++){ 
         if(line[i]>='0' && line[i]<='9') n=10*n + (line[i]-zero); 
         else { 
           arr[row][col++]=n; 
           n=0; 
         } 
       } 
       row++; 
     } 
     fclose(myFile); 

     // we now have a row x col array of integers in the var: arr 
     printf("arr[1][1] = %d\n", arr[1][1]); // <-- 23 
     printf("arr[0][9] = %d\n", arr[0][9]); // <-- 10 
     printf("arr[1][5] = %d\n", arr[1][5]); // <-- 2 

    } else { 
     printf("Error: unable to open snumbers.txt\n"); 
     return 1; 
    } 
} 
+0

私は変数 'zero'が助けてくれるとは思っていません。特に、範囲チェックではそれを使用しないためです。 –

+0

変数0は48の値(0の場合はASCII)を保持し、 "n = 10 * n + line [i]"は機能しません。 "1"など –

+0

私は '' const int'でもない変数の代わりに '' 0''を使用します。キャストは不要です。文字リテラルは 'int'値です。 if(line [i]> = 0 && line [i] <= nine) '(適切な定義:' const int nine = '9'; ')を使用した場合、おそらく私は気にしないでしょう。しかし、私は 'if(line [i]> = '0' && line [i] <= '9')'が明確で、変換演算は 'n = 10 * n + line [i] '0'; '明瞭さを失うことなく、 - 実際には、明瞭さの点ではわずかな利得があります。 –