Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

how to scanf unknown amount of integer numbers into array in C?

I know that I can scanf certain amount of numbers with scanf for example for 3 numbers

scanf("%d %d %d",array[0],array[1],array[2]);

but how can I scan it if I didn't know how many numbers (integer, not float) I would input into an array before enter (NOT EOF)? for example

input : 12 43 23(enter) --> array[0]=12, array[1]=43, array[2]=23
input : 10 20 30 40 50(enter) --> array[0]=10, array[1]=20, array[2]=30, array[3]=40, array[4]= 50
etc..

It's about how to input the numbers into an integer array.

And if it's possible, I want to save it into an 2 dimensions array, for example

input : 12 43 23(enter) --> array[0][0]=12, array[0][1]=43, array[0][2]=23
input : 10 20 30 40 50(enter) --> array[1][0]=10, array[1][1]=20, array[1][2]=30, array[1][3]=40, array[1][4]= 50
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's how you can store things in a (dynamically allocated) array. This does assume that the line length is limited to 1000 chars though. (Code adapted from How do I use scanf() to take an arbitrary amount of integers?)

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

int main() {
    int val_size = 2;
    int* vals = (int*)malloc(val_size * sizeof(int)); // initial array size
    char buffer[1000]; // for reading in the line
    int pos, bytes_read, num;
    int num_read = 0;

    if (fgets(buffer, sizeof(buffer), stdin) != 0) {
        for (pos = 0; sscanf(buffer+pos, "%d%n", &num, &bytes_read) != EOF; pos += bytes_read) {
            // resize the array if needed
            if (num_read >= val_size) {
                val_size *= 2;
                vals = (int*)realloc(vals, val_size * sizeof(int));
            }

            // store the value in the array
            vals[num_read] = num;
            num_read++;
        }
    }

    // print the values to prove it works
    for (int i = 0; i < num_read; i++) {
        printf("%d ", vals[i]);
    }
    printf("
");

    free(vals); // important after you're done with it
}

You can wrap a while around the if to get multiple lines.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...