0

我需要用 pure 编写一个程序C。我希望用用户输入的浮点数填充一个数组,此时我的函数如下所示:

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 的手册页:

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 回答