验证数组的数字

时间:2014-04-13 18:55:04

标签: c arrays validation

目前我正在使用此功能:

void manually(int *data, int size){
        int i;
        printf("Enter numbers of the array:\n");
        if(data != NULL){
            for(i = 0; i < size; i++){
                 if ((scanf("%d", &data[i]) == 1) && (getchar() == '\n') && (data[i] > 0)){
                    printf("Number: %d entered\n", data[i]);
                } else {
                    printf("Invalid input\n");
                //  while(getchar() != '\n');
                    i = i - 1;
                }
            }
        } else {
            printf("Memory wasn't allocated\n");
        }
    }

但是,输入其他符号而不是数字时,它不起作用。我认为fgets()将是解决方案,但不知道我应该如何修改它。我是C的新人,绝对新手。感谢。

1 个答案:

答案 0 :(得分:-1)

当输入无效输入时,您必须刷新标准输入stdin,否则对scanf的后续调用将获得相同的无效输入,并且您将以无限循环结束。

执行此操作的一种方法是调用

fseek(stdin,0,SEEK_END);

有些人警告说这可能无法移植(在fseek上使用stdin)。

另一种方法是在到达换行符之前调用getchar()

while( getchar() != '\n' );

就像你评论的那条线一样。

所以整个事情变成了:

void manually(int *data, int size){
    int i;
    printf("Enter numbers of the array:\n");
    if(data != NULL){
        for(i = 0; i < size; i++){
            if ((scanf("%d", &data[i]) == 1) && (data[i] > 0)){
                printf("Number: %d entered\n", data[i]);
            } else {
                printf("Invalid input\n");
                while( getchar() != '\n' );
                i = i - 1;
            }
        }
    } else {
        printf("Memory wasn't allocated\n");
    }
}

请注意,您不需要

(getchar() == '\n')

进入if声明