阻止用户输入数组中超过指定数量的元素?

时间:2016-10-13 21:56:20

标签: c arrays dynamic-memory-allocation

我如何检查用户是否输入了他们指定的正确数量的元素?我会动态分配用户想要的n元素数组,但是如何防止它们输入的元素超过n元素?

我尝试创建一个名为int num_Elements的变量,并在每次用户输入元素时沿着scanf("%d", &array[i])在for循环中递增它,然后按if(num_Elements > length)进行检查(length是用户想要的元素数量,但它没有用。或许我没有正确实现它。任何人吗?

#include <stdio.h>
#include <stdlib.h>

int main() {
    int elements = 0;
    int length;
    int i;
    int *p;

    printf("Please enter the number of elements in your array: ");
    scanf("%d", &length);
    p = (int *)malloc(length * sizeof(int));

    if (p == NULL) {
        puts("Could not allocate memory");
    } else {
        printf("Enter the %d elements: ", length);
        for (i = 0; i < length; i++) {
            scanf("%d", &p[i]);
            elements++;
            if (elements > length)
                printf("You entered more than\n");
        }
    }

    printf("You entered ");
    for (i = 0; i < length; i++) {
        printf("%d ", *(p + i));
    }
    putchar('\n');
    return(0);
}

1 个答案:

答案 0 :(得分:1)

您无法阻止用户在提示符处输入的数字多于您在循环中使用scanf()读取的数字。标准输入是行缓冲的:用户键入的字符由终端和/或操作系统缓冲,直到用户点击回车键,然后scanf返回第一次在循环内调用它。

您可以将终端模式更改为raw并一次处理一个字节的输入,但这会非常麻烦。

以下是一个简单的替代方法:使用fgets()读取输入,用strtol()解析输入,如果输入的数量超过需要,则会抱怨:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char buf[256];
    char *p;
    int i, length;
    int *array;

    printf("Please enter the number of elements in your array: ");
    scanf("%d", &length);
    array = malloc(length * sizeof(int));

    if (array == NULL) {
        puts("Could not allocate memory");
    } else {
        getchar(); // read the pending linefeed
        printf("Enter the %d elements: ", length);
        if (fgets(buf, sizeof buf, stdin) {
            for (p = buf, i = 0; i < length; i++) {
                // you should check if a number was actually converted...
                array[i] = strtol(p, &p, 10);
            }
            while (isspace((unsigned char)*p) {
                p++;
            }
            if (*p != '\0') {
                printf("You entered extra data\n");
            }
        }
    }

    printf("You entered ");
    for (i = 0; i < length; i++) {
        printf("%d ", array[i]);
    }
    putchar('\n');
    free(array);
    return 0;
}