ここでは、入力ファイルを配列に読み込む完全なコードを示します。私は文字を読んで数値に変換する 'コンバーター'を作成しました。あなたは数字の間にスペースが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;
}
}
2つのforループを使用して、2つ目のテストは最初のテストでテストします。 –
入力データが確実にループを使用してアレイに読み込まれている場合。 for(){for(){}} –
あなたのサンプル入力データは5x20クレームと結びついていないようです。あなたは、各行に10の数字を持つ2行の数字を表示します。実際のデータ形式は何ですか? 'fscanf()'を使って数値を読み取る際の問題は何ですか? –