代码之家  ›  专栏  ›  技术社区  ›  dangerChihuahua007

如何扫描一行n个整数?

c
  •  3
  • dangerChihuahua007  · 技术社区  · 12 年前

    在c中,我可以使用 scanf 从标准输入中读取3个由空格分隔的整数,如下所示:

    #include <stdio.h>
    
    int main() {
        int a, b, c;
        scanf("%d %d %d", &a, &b, &c);
    }
    

    如果我不知道手前一行有多少整数呢?假设用户提供整数的数量:

    #include <stdio.h>
    
    int main() {
        int howManyIntegersToRead;
        scanf("%d", &howManyIntegersToRead);
        // Read in the integers with scanf( ... );
    }
    

    我需要malloc一个大小的数组 sizeof(int) * howManyIntegersToRead 字节。我如何真正将标准输入数据读取到分配的内存中?我无法使用 howManyIntegersToRead %ds。嗯,我可以,但肯定有更好的办法。

    4 回复  |  直到 12 年前
        1
  •  8
  •   Rahul Tripathi    12 年前

    您可以使用 for 循环:

    int i, size;
    int *p;
    scanf("%d", &size);
    p = malloc(size * sizeof(int));
    for(i=0; i < size; i++)
        scanf("%d", &p[i]);
    
        2
  •  2
  •   Aseem Goyal    12 年前
    #include <stdio.h>
    
    int main() {
        int howManyIntegersToRead;
        scanf("%d", &howManyIntegersToRead);
        // Read in the integers with scanf( ... );
        // allocate memory
        int a[howManyIntegersToRead];  
    
         for(int i=0;i<howManyIntegersToRead;i++)
            scanf("%d",&a[i]);
    }
    
        3
  •  1
  •   ikh    12 年前

    使用动态分配和循环。

    #include <stdio.h>
    #include <malloc.h>
    
    int main()
    {
        int count, i;
        int *ar;
    
        printf("Input count of integers: ");
        scanf("%d", &count);
    
        ar = malloc(count * sizeof(int));
        if (ar == NULL)
        {
            fprintf(stderr, "memory allocation failed.\n");
            return -1;
        }
    
        for (i = 0; i < count; i++)
        {
            scanf("%d", &ar[i]);
        }
    }
    
        4
  •  1
  •   Varvarigos Emmanouil    12 年前
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void) {
    
        int* integers, i = 0;
        do {
    
        integers = realloc(integers, sizeof(int) * (i + 1));
        if(integers == NULL){
            return -1;
        }
        printf("enter an integer: ");
        scanf(" %d", &integers[i]);
        printf("\nentered: %d\n", integers[i]);
    } while(integers[i++] != 0);//here put your ending of choice
    
    
    free(integers);
    return 0;
    }