1
    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;
Gupta
  • 7,679
  • 4
  • 29
  • 56
Dontor
  • 11
  • 1
  • 2
    Won't your inner loop run right past the end of the string if the last character of the string is not a `|`? – Frank May 07 '20 at 13:48
  • yeah, when i try it with "aa|b|" it works perfectly, but how to fix it? – Dontor May 07 '20 at 13:50
  • There's a way simpler way to create a substring: https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c – UnholySheep May 07 '20 at 13:50
  • Just stop if you reach the end: `while (k < str.size() && rule[k] != '|')` – Frank May 07 '20 at 13:50

2 Answers2

2

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);
}
molbdnilo
  • 55,783
  • 3
  • 31
  • 71
0

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("|"));
Gupta
  • 7,679
  • 4
  • 29
  • 56