c++ - 将句子分为单词的 vector

标签 c++ string function vector

    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/

相关文章:

C++ 编译错误

c++ - SFINAE 为什么我没有检测到 std::vector 的下标运算符?

c++ - STL std::map operator[] 在赋值的右侧

excel - 如何比较Excel中两个单元格中的两个日期?

c++ - 访问说明符不是万无一失的吗?

c++ - 在 C++ 中验证 GPS 字符串的最简单方法?

c - 从用户获取字符串,然后将其从屏幕上删除

c++ - 无法让我的指针发送对数组的引用

函数作为参数的 C++ 错误,对非常量的引用的初始值必须是左值

C - 如何拆分用户输入的字符串