To use fgets()/sscanf() as requested by OP, see below.
Using fgets()/strtol() offers better error handling than sscanf(). Recommend strtol()
To get the best answer, OP needs to provide info like how data is to be store (VLA, malloc, 1 at-a time), error handle concerns, etc.
Hard to tell why OP code did not work as the defalcation of array[] is missing, but it may have been too small for the test data and certain was not resized as needed for various data input.
void foo() {
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOForIOError();
int i = 0;
int n = 0;
int number;
// Count the numbers
while (sscanf(&buf[i], "%d %n", &number, &i) == 1) {
n++;
}
int num[n];
i = 0;
int j;
// scan again, this time save the numbers
while (sscanf(&buf[i], "%d %n", &num[i], &j) == 1) {
i = j;
}
// use the numbers
bar(num, n);
}
Above code could use likely skip the j and use while (sscanf(&buf[i], "%d %n", &num[i], &i) == 1);, but I need to double check some code-point issues.
strtol() is better than sscanf(). To use, suggest a helper function:
// return non-zero on failure
static int user_strtoi(char **s, int *result) {
char *endptr;
errno = 0;
long num = strtol(*s, &endptr, 10);
if (endptr == *s) return 1; // fail as nothing was parsed
if (errno != 0) return 2; // fail due to overflow
if (num < INT_MIN || num > INT_MAX) return 2; // fail due to overflow
*result = (int) num;
*s = endptr;
return 0;
}
getline()and then split the string with the character " " and you will have an array of your numbers as strings. Convert your numbers from string to integer. This will give you your desired integer array.stdinintoarray, tillscanfis successfullyintlimited byNor is it an "unknown number" such as 0,1,2,3,...