0

Currently I'm reading each character from the user and storing it into a char array called str. From there I'm trying to use a pointer to loop through the string until it sees a space, once a space is seen I want to take the characters already and create an array of strings. Is that possible? Reasons why I'm doing this is because I later want to use an execlp function to execute a process after my initial program was executed.

6
  • did you take a look at strtok? Commented Sep 20, 2018 at 23:44
  • I agree with @Osiris, it the words are delimited, then strtok should suffice Commented Sep 20, 2018 at 23:47
  • @Osiris No I haven't I'll take a look. Would I be able to pass the tokens as arguments to the execlp function? if you know anything about that? Commented Sep 20, 2018 at 23:50
  • Yes it should work. You can create an array of char pointers and pass them to the function. Commented Sep 20, 2018 at 23:52
  • @pennyBoy In the future, please copy and paste your code directly into your question, as opposed to including an image of the code. StackOverflow will automatically format any code indented with at least four spaces as code. Commented Sep 21, 2018 at 2:59

1 Answer 1

1

If you want to split the string into tokens separated by delimiters you could use the strtok function.

An example would be:

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

int main(void)
{
    int i, n;
    char str[] = "Hello World";
    char *token[4], *act_token;

    token[0] = strtok(str, " ");
    n=1;
    while(n<4 && (act_token=strtok(NULL, " ")))
    {
        token[n] = act_token;
        n++;
    }

    for(i=0;i<n;i++)
    {
        printf("%d: %s\n", i, token[i]);
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

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.