How can I fill in a double or int array from a single, arbitrarily long, formatted (e.g. space delimited) keyboard line?
For instance:
Enter the elements of the array:
2 32 12.2 4 5 ...
should result in
=> array[0] = 2
=> array[1] = 32 etc.
I know that I can use scanf as follows, but that does not solve my problem, since each element should be entered one by one.
/* Input data from keyboard into array */
for (count = 1; count < 13; count++)
{
printf("Enter element : %d: ", count);
scanf("%f", &array[count]);
}
Thanks.
I know that I can use scanf as follows, but that does not solve my problem, since each element should be entered one by one.
No. If you leave off the newlines, that would work perfectly fine.
Generally, it is a good idea to avoid using scanf()
, though -- it's not the most intuitive function to use (so to say). How about using fgets()
to read in the line then parse it using strtof()
?
char buf[LINE_MAX];
fgets(buf, sizeof buf, stdin);
char *s = buf, *endp;
int i = 0;
for (i = 0; i < 13; i++) {
array[i] = strtof(s, &endp);
s = endp;
}