while(!infile2.eof())
         
         
         {
         size_t found;
         string temp2, store, wordtobold;                  
         string command1 ("bold");
         size_t prev_pos = 0, pos = 0;
                     
                              
                              
         getline(infile2, temp2);
         store += temp2;
         
         found=store.find(command1);
         if (found!=string::npos)
         wordtobold = store.substr (found+4);   
         
      
             while( (pos = wordtobold.find(' ', pos)) != string::npos )
    {
        
        string wordtotag( wordtobold.substr(prev_pos, pos-prev_pos) );
         cout << wordtotag;
       
         

         prev_pos = ++pos;
    }
}

Here is my string,

temp2: How are you
wordtobold: are you

i want to use a while loop to check every word in wordtobold,
and my expected output should be:

are
you

But what i got from the above code is only

are

how can i output the word "you" ?

Because you use find() with one space, the end of the string does not have it. As a result, it doesn't see your last word.

i.e.
"are you".find(' ', 0)
==> found 3 --> print "are"
"are you".find(' ', 3)
==> not found --> no print

So what you need to do is that if it does not find anymore, just print out whatever substring from the location you found+1 to the end of string unless the string is already empty in the first place.

should i put inside the loop?
also how to detect the end of string?

one more question to ask..
how can i skip the first word?
e.g. read "you" from "are you"

Or you actually mean to print out the last word? You already have prev_pos variable to use. Just print the substring starting from prev_pos up to the string length.

nono,
my string is not known, "how are you" is just an example..
the string may be any sentence of different length..
how can i detect the end of string??

So you mean you need to find a specific string pattern? find() will give you the index location of the starting pattern. i.e. "how are you".find("you"); will return 8 which is found. I think if it returns -1, it means it doesn't find the pattern you are looking for.

The end of string is a character '\0'. If you create your own string (using pointer), you must append the character at the end of your string, or the string will be left open and may not be properly used by anything else.

Use .rfind() to search for the last space. .rfind() starts searching from the end of the string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.