scanf验证用户输入

时间:2012-09-29 20:27:37

标签: c pointers scanf

我需要用纯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'第

2 个答案:

答案 0 :(得分:2)

不要使用scanf()进行用户输入。它被编写为与格式化数据一起使用。用户输入和格式化数据与白天的夜晚不同。

使用fgets()strtod()

答案 1 :(得分: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;