Hey everyone, long time lurker first timer poster :icon_cool:

For the past week I've been trying to come up with a way of doing this but I just can't seem to think and implement anything that will work.

Basicly I have a string such as "Welcome to my program"
I want to be able to address each word in that such as putting them into a structure so it could work like this:

word1.txt = "Welcome"
word2.txt = "to"
word3.txt = "my"
word4.txt = "program"

However the string will be dynamic and I've read a little bit about strtok seperate the words with a token but I can't figure out any method to make this work.

Any help is appreciated.

char s1[100] = "Lets see what it does?", s2[100]=" ", *tok;


    tok = strtok(s1, s2);

    while(tok != NULL)
    {
            printf("%s\n", tok);
            /*Put tok in your struct here*/
            tok = strtok(NULL, s2);


    }

Edited 3 Years Ago by Dani: Formatting fixed

I don't understand why you want to put words into a structure. A structure has fixed number of fields (four in your case). Do you want to parse four words phrases only?!

Apropos, structure access looks like:

txt.word1 = ...
txt.word2 = ...
...

Better use arrays or (much more better in this case) std::vector<std::string> instead of structures. However if you want (or should use) a structure then present this structure definition...

Using a vector was exactly what was needed, thanks!
I am using:

std::vector <string> var;

while(tok != NULL)
{
parse spaces..
var.push_back(tok)
}
This article has been dead for over six months. Start a new discussion instead.