Robust string handling in C is never easy.
Here is the procedure that immediately appeared for me. Use strtok()to split a string into separate tokens and then convert each token to an integer value with strtol().
: strtok() ( 0 ). , . , strtok(). , strtok() , .
, strtol() ; , . - , 0, , , .
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void stringToIntList(char *str, int *arr, size_t arrSize, size_t *count)
{
char *token;
char *localStr = malloc(strlen(str) + 1);
if (!localStr)
{
exit(-1);
}
strcpy(localStr, str);
*count = 0;
token = strtok(localStr, " ");
while (token && *count < arrSize)
{
char *chk;
int val = (int) strtol(token, &chk, 10);
if (isspace(*chk) || *chk == 0)
{
arr[(*count)++] = val;
}
else
{
printf("\"%s\" is not a valid integer\n", token);
}
token = strtok(NULL, " ");
}
free(localStr);
}
int main(void)
{
int values[5];
char *str = "14 22 33 48 5q";
size_t converted;
stringToIntList(str, values, sizeof values / sizeof values[0], &converted);
if (converted > 0)
{
size_t i;
printf("Converted %lu items from \"%s\":\n", (unsigned long) converted, str);
for (i = 0; i < converted; i++)
printf("arr[%lu] = %d\n", (unsigned long) i, arr[i]);
}
else
{
printf("Could not convert any of \"%s\" to equivalent integer values\n", str);
}
return 0;
}