Hi guys! Sorry for my Englisg
Faced with such a problem: given a string. It is necessary to put of all the words from a string in the vector, but it does'nt work. I have read this reference http://www.cplusplus.com/reference/string/string/erase/.
And use 0 and count to clean the string by every iteration.
I think problem in erase(), but who knows?
Thanks!
If your string contains a bunch of words in it separated by white spaces then you could use a stream to load them into vector obj
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <sstream>
///in main make a stringstream object
stringstream ss; ss.str (""); ss.clear ();
//s is your string and v is your vector
ss <<s; //load string into stream
string temp;
///load words into vector
while (ss>> temp)
{
v.push_back (temp);
}
first time through, word ends up being a null string, count is 1, so s.erase() call ends up just deleting the first character. problems compound from there.
rather than messing with all these iterators and begin() end() business, consider that strings are actually themselves vectors of characters. This means that you can access them with array subscript notation. Doing so makes this really easy:
1 2 3 4 5 6 7 8 9 10 11
for( int c = 0; c < s.size() - 1; c++ )
{
if( s[c] == ' ' )
{
if( word != "" )
v.push_back( word );
word = "";
}
else
word += s[c];
}
*edit* Just noticed that I'm not pushing the last word in the string with the above. fixing it now
for( int c = 0; c < s.size(); c++ )
{
if( s[c] == ' ' )
{
if( word != "" )
v.push_back( word );
word = "";
}
else
word += s[c];
}
if( word != "" )
v.push_back( word );
stringstreaming it like Andy suggested above might be the way to go though.
Thanks a lot for your answers! Problem is fixed
andy1992, interesting approach, I will study!
Esslercuffi, really every symbol were deleted for each iteration, I forgot the brackets in the operator if !