0

I currently am trying to extract a substring within a bufferline. The goal is to parse the string by whitespace and symbols to compile later. The line I'm trying to parse is the first line of my file.

void append(char* s, char c)
{
    int len = strlen(s);
    s[len] = c;
    s[len+1] = '\0';
}

int main(void){    
    char str[] = "program example(input, output);";

    char *f = str;
    char *b = str;

    char token[10];

    if(*f != '\0'){
        while (*f != ' ')
        {
            append(token,*f);
            f++;
        }
        f++;
        printf("%s",token);
        token[9] = '\0';
    }
    return 0;
}

Am I clearing the token string wrong? The code only returns:

program

but it should return

program
example(input,
output);
0

1 Answer 1

1

There are a few things fundamentally wrong with your code (possibility of buffer overflow in your append() function, etc). I have changed just enough to allow the code to produce the desired result, to my understanding.

int main(void){    
    char str[] = "program example(input, output);";

    char *f = str;

    char *token=(char *)malloc((strlen(str)+1)*sizeof(char));
    char *b = token;

    while(*f != '\0'){
        while (*f && *f != ' ')
        {
            *b++=*f;
            f++;
        }
        if(*f) f++;
        *b=0;
        b=token;
        printf("%s\n",token);
    }
    free(token);
    return 0;
}
$ ./a.out 
program
example(input,
output);

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! My goal is to separate the each token. This should get me on the right track now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.