Если это ваш точный формат, то, возможно, fscanf
/ sscanf
может выполнить эту работу за вас? то есть.
#include <stdio.h>
int main(void)
{
int nums[6];
char line[] = "Cheryl 2 1 0 1 2 0";
sscanf(line, "%*s %d %d %d %d %d %d", &nums[0], &nums[1], &nums[2], &nums[3], &nums[4], &nums[5]);
printf("%d %d %d %d %d %d\n", nums[0], nums[1], nums[2], nums[3], nums[4], nums[5]);
return 0;
}
Выход:
2 1 0 1 2 0
А затем просто проверьте возвращаемое значение, чтобы убедиться, что правильное количество чисел было прочитано.
РЕДАКТИРОВАТЬ: Для произвольной суммы:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strchr_ignore_start(const char *str, int c)
{
if (c == '\0') return strchr(str, c); /* just to be pedantic */
/* ignore c from the start of the string until there's a different char */
while (*str == c) str++;
return strchr(str, c);
}
size_t extractNums(char *line, unsigned *nums, size_t num_count)
{
size_t i, count;
char *endptr = line;
for (i = 0, count = 0; i < num_count; i++, count++) {
nums[i] = strtoul(line, &endptr, 10);
if (line == endptr) /* no digits, strtol failed */
break;
line = endptr;
}
return count;
}
int main(void)
{
unsigned i, nums[9];
char line[] = "Cheryl 2 1 0 1 2 0 0 1 2";
char *without_name;
/* point to the first space AFTER the name (we don't want ones before) */
without_name = strchr_ignore_start(line, ' ');
printf("%u numbers were successfully read\n",
(unsigned)extractNums(without_name, nums, 9));
for (i = 0; i < 9; i++)
printf("%d ", nums[i]);
putchar('\n');
return EXIT_SUCCESS;
}