【问题标题】:Preventing the user from entering more than specified number of elements in an array?防止用户在数组中输入超过指定数量的元素?
【发布时间】:2016-10-13 21:56:19
【问题描述】:

我将如何检查用户输入的元素数量是否正确?我将动态分配用户想要的n 元素数组,但我将如何防止它们输入比n 元素更多的元素?

我尝试创建一个名为 int num_Elements 的变量,并在每次用户输入一个元素时在 for 循环中沿 scanf("%d", &array[i]) 递增它,然后通过 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);
}

【问题讨论】:

  • 他们只能在程序要求时输入一些内容。不要要求超过n 个元素。
  • 请出示您的代码。了解如何创建 MCVE (minimal reproducible example)。
  • for (int i = 0; i &lt; numElements; i++) { // code that asks for input }
  • 需要比“它不起作用”更多的细节。邮政编码、输入、输出、预期输出。
  • @HPotter,感谢您添加代码,但您需要解释它是如何“不起作用”的。我没有发现明显的错误,当我在我的系统上运行您的程序时,它按预期工作。

标签: c arrays dynamic-memory-allocation


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2011-05-09
    • 2022-01-16
    • 2019-06-17
    • 1970-01-01
    相关资源
    最近更新 更多