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";
}
我只想将“aa”和“b”分开,并在 vector 中将其作为字符串。它引发了这个异常:
Unhandled exception at 0x7A14E906... An invalid parameter was passed to a function that considers invalid parameters fatal;
最佳答案
这个循环
while (rule[k] != '|' )
{
curr.push_back(rule[k]);
k++;
}
找到最后一个
'|'
后,它将继续前进,结果是未定义的行为。使用
stringstream
和'|'
作为“行”分隔符,可以更轻松地解决此问题。std::istringstream is(rule);
std::string word;
while (std::getline(is, word, '|'))
{
str.push_back(word);
}
关于c++ - 将句子分为单词的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61659315/