処理手順
読み込むデータ数よりも大きな配列を用意する
データがなくなったところで繰り返しを終える
条件設定: データの個数は1000を越えないものと想定する
#define SIZE 1000 ... int data[SIZE]
データを一度に1つ宛、繰り返し処理により読み込むことにする
while(データを読み込むことができるか?) { 読み込んだデータを配列要素に格納する; }
counter = 0; while(データを読み込むとができるか?) { data[counter] = 読み込んだデータ; counter++; // データを読み込む毎にカウンタの値を1つ増やす }
scanf文を使用
一度に1個のデータを読むので, データが読めた場合は1が返されることを利用する.
while(scanf("%d", &n) == 1) { data[counter] = n; conter++; }
while(scanf("%d", &data[counter]) == 1) { conter++; }
#include <stdio.h> #define SIZE 1000 // 処理できるデータの最大個数 main() { int data[SIZE]; // データ int counter = 0; // カウンタ /* 整数値を配列に読み込む. この繰り返し処理を終えたとき, 読み込んだデータの個数が counter に格納されている. */ while(scanf("%d", &data[counter]) == 1) { conter++; } printf("%d個のデータを読み込みました.\n", counter); ... }
#include <stdio.h> #include <stdlib.h> #define SIZE 1000 // 処理できるデータの最大個数 main() { int data[SIZE]; // データ int counter = 0; // カウンタ int n; /* 整数値を配列に読み込む. この繰り返し処理を終えたとき, 読み込んだデータの個数が counter に格納されている. */ while(scanf("%d", &n) == 1) { if(counter >= SIZE) { printf("Error: データ数が配列サイズ(%d)を越えました\n",SIZE); exit(1); } data[counter] = n; counter++; } printf("%d個のデータを読み込みました.\n", counter); ... }
プログラムの途中にprintf文を入れ, 処理途中の変数の値を表示して,動作を確認する
以上