My input consists of a sequence of integers, that need to be saved in a dynamic array. The number of integers is the first integer of the sequence. For example: 3 23 7 -12
or 5 -777 3 56 14 7
The sequence is ONE input.
How can i scan such an input?
For scanf("%i %i %i ...",)
i need to know the amount of integers in advance, which i dont.
CodePudding user response:
Use multiple scanf
calls. First read the count, then read the values in a loop.
int count;
scanf("%i", &count);
int values[count];
for (int i=0; i<count; i ) {
scanf("%i", &values[i]);
}
Note that this doesn't include error checking for invalid values.
CodePudding user response:
You can do it with a do-while loop:
int status = 0;
do {
status = scanf("%d", &placeToStoreVariablesAt);
} while(status);
Note that scanf() returns number of elements of correct type entered. If a char is entered, status becomes 0 and therefore program exits loop.