When i’m calling to the function below, it adds my input to the vector, but consistently adds 6 extra cells to the vector. Any ideas why does it happening?
This is the relevant function:
void seperate_words(string str1, vector<struct wordstype> &vec1)
{
string temp_str;
string::iterator is=str1.begin();
wordstype input_word;
while (is<str1.end())
{
if (((*is)!='-')&&((*is)!='.')&&((*is)!=',')&&((*is)!=';')&&((*is)!='?')&&((*is)!='!')&&((*is)!=':'))
{
temp_str.push_back(*is);
++is;
}
else
{
input_word.word=temp_str;
vec1.push_back(input_word);
is=str1.erase(is);
temp_str.clear();
}
}
input_word.word=temp_str;
vec1.push_back(input_word);
temp_str.clear();
}
the relevant interval of main program that calls the func is:
**while(end_flag==-1){
cin>> temp_string;
end_flag=temp_string.find(end_str);/*indicates whether the end sign is precieved*/
seperate_words(temp_string,words_vecref);/*seperats the input into single words and inserts them into a vector*/
}
int x=words_vec.size();
cout<<x<<" "<<std::endl;
for (vector<struct wordstype>::iterator p_it=words_vec.begin();p_it<words_vec.end();p_it++)
{cout<<(*p_it).word<<" ";}**
for example: i’m walking down the street, should increase my vector size by only 6 elements(and not 12)
output expected:only six cells, in each oe of them will be a word from the input in the order of entry.
Does your string have six punctuation marks at the end?
When the text ends with a punctuation mark, you add an extra empty string to the vector ( because you unconditionally add to the vector outside the while loop)
If you have several of these you have several empty strings (this time inside the while loop).
These empty strings can also occur in the middle of the text.
This because you when pushing back don’t test where you actually encountered some text.
You can fix this be testing whether temp_str is not empty before calling push_back in the while loop and after the while loop.