user41836
user41836

Reputation: 27

Take in as many inputs as user gives with scanf in C

How do you take in as many inputs as the user gives if you have no idea how many they'll give? It'll be things like:

1 2 3
4 5
6 

and I just need a way to read in all those integers, without setting any limit.

Upvotes: 0

Views: 100

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

Do you need to store all the integers at once in an array, or can you process each integer as it is read? Is there any significance to the fact that there are three integers on the first line and two on the second, or is that irrelevant?

If you don't need to store all the integers at once and you don't need to know when you reach an end of line, then scanf() or fscanf() will work fine.

int value;
while (scanf("%d", &value) == 1)
    process(value);

If you need to store all the integers into an array but don't need to worry about where line breaks occur, then you probably need to use dynamic memory allocation so that the array grows. That's fiddlier:

int *array = 0;
size_t a_size = 0;
size_t a_used = 0;
int value;

while (scanf("%d", &value) == 1)
{
    if (a_used == a_size)
    {
        size_t n_size = (a_size + 1) * 2;
        int *n_data = realloc(array, n_size * sizeof(*n_data));
        if (n_data == 0)
            …handle memory allocation failure…
        a_size = n_size;
        array = n_data;
    }
    array[a_used++] = value;
}

for (size_t i = 0; i < a_used; i++)
    printf("[%zu] = %d\n", i, array[i]);

Note that the 'handle memory allocation failure' code should abort the processing, possibly also releasing the currently allocated array, or possibly just continuing the processing with the existing array (break would work). Note how the code avoids too much copying by doubling the memory in the array, and avoids leaking memory by not assigning the return value from realloc() until it is known to be non-null. If you're worried by excess memory allocation at the end, you can do a 'shrinking' realloc() after the loop, specifying the final size of the array.

If in fact you need to know where the line breaks were, then you have to work still harder. You need to keep an array of dynamic arrays; you need to keep a record of the length of each line; and you have to stop using scanf() or fscanf() because they don't care in the slightest about lines. You use fgets() or readline() to read a line (and in the case of fgets(), you'll need to worry about whether you got the whole line), and then you'll use sscanf() to iteratively parse the whole line.

Upvotes: 0

P0W
P0W

Reputation: 47784

May be like this :-

int input;

while (fscanf(stdin, "%d", &input) ==1) //Loop terminates on error or EOF
{
  /* process each input 
     Store in array or whatever
  */
}

Upvotes: 4

Related Questions