扫描无符号直到 EOF 无法正常工作

Scanning unsigned until EOF not working properly

我正在尝试扫描无符号整数,直到 EOFCtrl-D 在我的平台上)。扫描的整数应该只是正数,因为 0 被认为是无符号的,我需要检查是否输入了 0

    int cnt1 = 0;
    unsigned *list1;
    list1 = malloc(sizeof(unsigned));

    printf("Enter positive integers to the first list:");
    while (scanf("%u", list1 + cnt1)) {  /* getting the first list */
        if (*(list1 + cnt1) == 0) {  /* checks to see if the number entered is 0 */
            printf("\nError - you must enter positive numbers");
            exit(-1);
        }
        cnt1++;
        list1 = realloc(list1, (sizeof(unsigned) + cnt1 * sizeof(unsigned)));
    }
    printf("\n");

    free(list1);

我的目标是用户键入整数直到按下 Ctrl-D,所有无符号整数都将保存在 list1 指针上。但是却发生了这种情况:

Enter positive integers to the first list:23 10
Error - you must enter positive numbers

出于某种原因,代码仅在我按 Ctrl-D 两次并将数字注册为 0.

时停止

scanf("%u", list1 + cnt1) returns:

  • 1如果转换成功
  • 0 如果待定输入无法转换为数字
  • EOF 如果流位于文件末尾。

因此你应该写:

while (scanf("%u", list1 + cnt1) == 1) {

此外,如果需要附加数字,最好只重新分配数组:

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

unsigned *read_list(int *countp) {
    int count = 0;
    unsigned *list = NULL;
    unsigned *new_list;
    unsigned num;

    printf("Enter positive integers to the first list: ");
    while (scanf("%u", &num) == 1) {
        if (num == 0) {  /* checks to see if the number entered is 0 */
            printf("\nError - you must enter positive numbers\n");
            continue;
        }
        new_list = realloc(list, sizeof(*list) * (count + 1));
        if (new_list == NULL) {
            printf("\nError - cannot allocate memory\n");
            free(list);
            *countp = -1;
            return NULL;
        }
        list = new_list;
        list[count++] = num;
    }
    printf("\n");
    *countp = count;
    return list;
}