-4

I have a char* formatted like:

* SEARCH 1 2 3 ...

with a variable number of integers separated by spaces. I would like to write a function to return an int[] with the integers after * SEARCH.

How should I go about writing this function?

Dia McThrees
  • 53
  • 1
  • 6
  • 1
    Did you have a question, or did you just want someone to write it for you? Here's a hint: You might want to look at `strtok()`. – Jonathan Wood Nov 25 '14 at 04:33
  • see this:http://stackoverflow.com/questions/9210528/split-string-with-delimiters-in-c – Suchit kumar Nov 25 '14 at 04:34
  • @JonathanWood I have no idea how to write it. I'm used to python. It's not homework or anything, it'd be nice to just get the function. – Dia McThrees Nov 25 '14 at 04:34
  • Then take my hint and do some research. Stackoverflow is designed for questions, and not for asking people to write the code for you. – Jonathan Wood Nov 25 '14 at 04:36
  • You might not even need `strtok()`. `strto[u]l[l]()` should automagically let you parse such a simple structure. – EOF Nov 25 '14 at 09:27

1 Answers1

0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *f(const char *s, int *n /* out */){
    if(strncmp(s, "* SEARCH", 8)!=0){
        fprintf(stderr, "format error!\n");
        *n = 0;
        return NULL;
    }
    s += 8;
    const char *p = s;
    int v, len, status;
    int count = 0;
    while((status=sscanf(p, "%d%n", &v, &len))==1){
        ++count;
        p +=len;
    }
    if(status==0){
        fprintf(stderr, "format error!\n");
        *n = 0;
        return NULL;
    }
    int *ret = malloc(count * sizeof(*ret));
    p = s;
    count = 0;
    while(EOF!=sscanf(p, "%d%n", &v, &len)){
        ret[count++]=v;
        p +=len;
    }
    *n = count;
    return ret;
}

int main (void){
    int i, n, *nums = f("* SEARCH 1 2 3", &n);

    for(i=0; i<n; ++i)
        printf("%d ", nums[i]);
    printf("\n");
    free(nums);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70