3

If I want to get input 3 numbers, I can write code like this:

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

but how can I dynamically get the number of inputs from one line?

For example, if user enters N(number), then I have to get N integer number inputs from one line like above.

The input and output should be :

how many do you want to enter: 5
1 2 3 4 5
sum: 15
user7159879
  • 637
  • 2
  • 8
  • 14

2 Answers2

5

Since scanf returns the amount of variables filled you can loop until scanf has no more value to read or the count is matched:

int count = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);
int val = 0;
int sum = 0;
int i = 0;
while(scanf("%d ", &val) == 1 && i++ < count)
  sum += val;
Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
  • If I enter 1 2 3 4 5, these numbers are in standard input buffer. so, does scanf read input from this buffer although I just enter one line?? That's why these instructions works?? – user7159879 May 03 '17 at 15:37
1

As you don't know the size of inputs previously it's better to create a dynamic array based on the input size provided by the user. Input the size of the array and create an array of that size. Then you can easily loop through the array and do whatever you want with it.

int count = 0, sum = 0;
printf("how many do you want to enter: ");
scanf("%d", &count);

int *num = malloc(sizeof(int)*count);

for(int i = 0; i < count; i++) {
    scanf("%d ", &num[i]);
    //sum += num[i];
}
Rajeev Singh
  • 3,292
  • 2
  • 19
  • 30