For example, input is:
12 23 32 41 45
22 11 43
lines end with '\n'
,
I want to save the numbers to a[]
and b[]
;
a[] = {12, 23, 32, 41, 45}
b[] = {22, 11, 43}
The point is, I don't know how many numbers are in each line.
If I know line1 ha n
numbers, and line2 has m
numbers, I will use for
loop:
for(int i = 0; i < n; i++) scanf("%d", a+i);
for(int i = 0; i < m; i++) scanf("%d", b+i);
If you would like to continue using a scanf
approach, I would recommend the negated scanset %[^]
format specifier.
scanf("%[^\n]", pointerToCharArray)
This should read in any number of characters up to but not including the character specified (which, in our case, is a newline). If you'd like to discard the newline, read it in as follows:
scanf("%[^\n]\n", pointerToCharArray)
More information about the negated scanset specifier.
From this point, it is a simple matter to use strtok()
to tokenize the output of the scanf into number arrays.