Dontor
Dontor

Reputation: 11

Separate a sentense into a vector of its words

    std::string rule = "aa|b";
    std::string curr;
    std::vector<std::string> str;
    int k = 0;
    while (k < rule.size())
    {
        while (rule[k] != '|' )
        {
            curr.push_back(rule[k]);
            k++;
        }
        str.push_back(curr);
        curr.clear();
        k++;
    }
    for (size_t i = 0; i < str.size(); i++)
    {
        std::cout << str[i] << "\n";
    }

i want just to separate "aa" and "b" and have it in a vector as strings. It throws me this exception:

Unhandled exception at 0x7A14E906... An invalid parameter was passed to a function that considers invalid parameters fatal;

Upvotes: 1

Views: 45

Answers (2)

TonySalimi
TonySalimi

Reputation: 8427

You can simply use boost::split as well:

   #include <boost/algorithm/string.hpp>

   std::vector<std::string> strs;
   boost::split(strs, "this|is|a|simple|example", boost::is_any_of("|"));

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66371

This loop

while (rule[k] != '|' )
{
    curr.push_back(rule[k]);
    k++;
}

will just keep going without end after you've found the last '|', with undefined behaviour as a result.

This is easier to solve with a stringstream and '|' as "line" separator.

std::istringstream is(rule);
std::string word;
while (std::getline(is, word, '|'))
{
    str.push_back(word);
}

Upvotes: 2

Related Questions