0

私は純粋なプログラムを書く必要がありCます。ユーザーが入力したfloatで配列を埋めたいのですが、現時点での私の関数は次のようになります。

int fillWithCustom(float *array, int size) {
    float customNumber;
    for (i = 0; i < size; i++)
        for (j = 0; j < size; j++) {            
            printf("\n Enter [%d][%d] element: ", i , j);
            scanf("%f", &customNumber);
            *(array+i*size+j) = customNumber;
        }
    return 1;
}

しかし、間違った数値または文字を入力すると、反復は終了し続けます...(たとえば、最初の要素として「a」を入力すると、両方のサイクルでscanfなしで反復され、配列は0'sで埋められます。

4

2 に答える 2

2

scanf()ユーザー入力には使用しないでください。フォーマットされたデータで使用するために作成されました。ユーザー入力とフォーマットされたデータは、昼と夜と同じように異なります。

とを使用fgets()strtod()ます。

于 2012-09-29T21:04:14.417 に答える
1

scanfの戻り値を確認してください。scanfのmanページから:

RETURN VALUE
   These functions return the number of input items  successfully  matched
   and assigned, which can be fewer than provided for, or even zero in the
   event of an early matching failure.

   The value EOF is returned if the end of input is reached before  either
   the  first  successful conversion or a matching failure occurs.  EOF is
   also returned if a read error occurs, in which case the error indicator
   for  the  stream  (see ferror(3)) is set, and errno is set indicate the
   error.

データを取得するまでデータを読み続けるには、次のようにします。

while(scanf("%f", &customNumber) == 0);

ユーザーが不正なデータを入力した場合に失敗したい場合は、次のようにします。

if(scanf("%f", &customNumber) == 0)
    break;
于 2012-09-29T20:30:14.987 に答える