You never change the conditional of your while
loop.
Each time your loop circulates around it always find the last space in a string that never changes throughout the loop body. This causes you to find the same word repeatedly, each time appending it to the next slot in your array until you run out of slots. And since you never check the i
index against array_size
to stop the madness, you eventually overrun your array and straight into undefined behavior:
int parse140(string str_array[], int array_size, string str, int &i)
{
int word_begin = 0;
int length = 0;
while(word_begin <= str.rfind(" ")) // str NEVER changes
{
word_begin = word_start(str, word_begin);
//check if word_begin is less than 0.. break
if(word_begin < 0)
break;
length = word_length(str, word_begin);
if(length < 0)
length = str.length() - word_begin;
str_array[i]= str.substr(word_begin, length);
i++;
}
return i;
}
Honestly, the fastest way to fix this is to not do it how you're doing it. Were I faced with this, I would do it like this, which you may find a little more .. brief:
#include <iostream>
#include <sstream>
int parse140(std::string str_array[], int array_size, std::string str, int &i)
{
std::istringstream iss(str);
for (i=0; i<array_size && (iss >> str_array[i]); ++i);
return i;
}
Alternative Approach
Without using string streams, this is still fairly reasonable using the algorithms library, stripping all whitespace and only extracting words.
int parse140(string str_array[], int array_size, string str, int &i)
{
std::string::iterator it = str.begin();
for (i=0; i<array_size && it != str.end(); ++i)
{
// locate first non-whitspace character
it = std::find_if_not(it, str.end(), is_space());
if (it != str.end())
{
// find first whitespace or end-of-string
std::string::iterator itEnd = std::find_if(it, str.end(), is_space());
str_array[i].assign(it, itEnd);
it = itEnd;
}
}
return i;
}