Search code examples
cinputscanf

How to get multiple inputs in one line in C?


I know that I can use

scanf("%d %d %d",&a,&b,&c): 

But what if the user first determines how many input there'd be in the line?


Solution

  • You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int ac, char **av)
    {
            int numInputs;
            int *input;
    
            printf("Total number of inputs: ");
            scanf("%d", &numInputs);
    
            input = malloc(numInputs * sizeof(int));
    
            for (int i=0; i < numInputs; i++)
            {
                    printf("Input #%d: ", i+1);
                    scanf("%d", &input[i]);
            }
    
            // Do Stuff, for example print them:
            for (int i=0; i < numInputs; i++)
            {
                    printf("Input #%d = %d\n", i+1, input[i]);
            }
    
            free(input);
    }