Вы должны читать в цикле, пропуская пробелы (см. isspace(3)
) и во внутреннем цикле, while (isdigit(getchar()))
(см. isdigit(3)
)
Я напишу некоторый код (еслиВы не хотите быть избалованным, не читайте ниже, пока вы не будете удовлетворены своим решением):
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* this macro calculates the number of elements of an array.
* you must be carefull to always pass an array (not a pointer)
* to effectively get the number of elements */
#define SIZE(arr) ((sizeof arr) / (sizeof arr[0]))
int main()
{
int n = 0;
int a[100];
/* this has to be an int (not a char) see getchar() manpage */
int last_char = 0;
/* while n < number of elements of array a */
while (n < SIZE(a)) {
/* read the character into last_char and check if it is
* a space, tab or newline */
while (isspace(last_char = getchar()))
continue;
/* last_char is not a space, it can be EOF, a minus sign,
* a digit, or something else (not a number) */
if (last_char == EOF)
break; /* exit the outer loop as we got no more input data */
int neg = (last_char == '-'); /* check for negative number */
if (neg) last_char = getchar(); /* advance */
/* check for digits */
if (isdigit(last_char)) {
/* digits are consecutive chars starting at '0'. We are
* assuming ASCII/ISO-LATIN-1/UTF-8 charset. This doesn't
* work with IBM charsets. */
int last_int = last_char - '0';
while (isdigit(last_char = getchar())) {
last_int *= 10; /* multiply by the numeration base */
last_int += last_char - '0'; /* see above */
}
/* we have a complete number, store it. */
if (n >= SIZE(a)) { /* no more space to store numbers */
fprintf(stderr,
"No space left on array a. MAX size is %d\n",
SIZE(a));
exit(EXIT_FAILURE);
}
if (neg) last_int = -last_int;
a[n++] = last_int;
}
/* next step is necessary, because we can be on a terminal and
* be able to continue reading after an EOF is detected. Above
* check is done after a new read to the input device. */
if (last_char == EOF)
break;
} /* while (n < SIZE(a) */
printf("Number list (%d elements):", n);
int i;
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
}
printf("\n");
exit(EXIT_SUCCESS);
} /* main */