I am trying to read the following input (Variable numbers of integers in a single line which are separated by spaces) through console using C in efficient manner.
Input:
4
3 1 2
6 1 1 1 4
17 2 3 2
12
The number of input lines (here 4, given in first line) are known but number of integers in a line are not known. One of the similar question which I found is given here, and solution is not working for me (I think I have understood this wrong).
while (i < ARRAY_SIZE && scanf("%d", &a[i++] == 1);
I wrote one simple program using this solution:
#include<stdio.h>
int main()
{
int i=0,ARRAY_SIZE=3,a[ARRAY_SIZE];
while (i < ARRAY_SIZE && (scanf("%d", &a[i++]) == 1));
printf ("%d %d %d %d\n",a[0], a[1], a[2], a[3],i);
}
For the above program 2 inputs and corresponding outputs are as follows:
Input-1:
2 3\n
4 5\n
Output-1:
2 3 4 0 3
Input-2:
1 4 6 7 4 3 3\n
Output-2:
1 4 6 0 3
But this is not what I was expecting from this program. Here I was trying to read only one line of integers, store them in an array and terminate as soon as one line is over so that If I want to read multiple line I am left with the option of using loop for those many lines (4 in the original input).
It may happen that I am not able to understand above solution and trying to use it at inappropriate place. So guys please help me regarding taking space separated input of integers from console in an efficient fashion.