7

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?

Steve Summit
  • 38,132
  • 7
  • 61
  • 86
Soham
  • 203
  • 1
  • 2
  • 6

3 Answers3

6

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);
}
ccKep
  • 5,656
  • 16
  • 28
0

Read in the whole line, then use a loop to parse out what you need.

To get you started:

1) Here is the manual page for getline(3): http://man7.org/linux/man-pages/man3/getline.3.html

2) Some alternatves to getline: How to read a line from the console in C?

3) Consider compressing spaces: How do I replace multiple spaces with a single space?

4) Use a loop for parsing. You might consider tokenizing: Tokenizing strings in C

5) Be careful and remember that your user could enter anything.

Community
  • 1
  • 1
Madmartigan
  • 133
  • 1
  • 7
0
#include <conio.h>
#include <stdio.h>
main()
{
    int  a[100],i,n_input,inputs;
    printf("Enter the number of inputs");
    scanf("%d",&n_input);

    for(i=0;i<n_input;i++)
    {
        printf("Input #%d: ",i+1);
        scanf("%d",&a[i]);
    }

    for(i=0;i<n_input;i++)
    {
        printf("\nInput #%d: %d ",i+1,a[i]);
    
    }

}    
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 29 '21 at 15:39