C++ 在字符串中找不到 ";"

标签 c++ if-statement vector

我的问题是我定义了这样一个字符串:

string messages = "This is an option; This is a really long option; Another One For Testing Sake; This is the last one I swear; You lied to me!";

';'字符串中的字符将被视为分隔符。在宏伟的计划中,这个字符串被调用到一个函数中 res.addMessages(messages); 其代码是:

void ConflictResMenu::addMessages(string messages) {

    int idx = 0;
    for (int i = 0; i < messages.length(); i++) {

        cout << messages.find_first_of(';') << endl;
        if (messages[i] == this->delim) {

            this->split_messages.push_back(messages.substr(idx, i));
            idx = i + 1;

        }
    }
}

这个问题是 if 子句在所有错误的时间被调用,所以输出结果如下:

This is an option
This is a really long option; Another One For
Another One For Testing Sake; This is the last one I swear; You lied to me!
This is the last one I swear; You lied to me!

老实说,我不知道这里发生了什么。如果有人可以帮助或建议更好的方法来解决这个问题,我将不胜感激。

最佳答案

您可能会使用 std::istringstreamstd::getline拆分字符串:

std::istringstream is(messages);

std::string msg;
while (std::getline(is, msg, ';'))
{
    split_messages.push_back(msg);
}

关于C++ 在字符串中找不到 ";",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18464168/

相关文章:

shell - 如何否定/"reverse mean"这个搜索——也就是 "!"的意思

r - 如何在R中使用if containsimilar,then

C++ replace_if on vector with struct in STL

r - 如何计算R中向量中有序的相同元素的数量?

c++ - 如果通过new创建对象,成员函数的局部变量在哪里创建?

c++ - 为什么 std::pair 暴露成员变量?

c++ - Windows 下 HUGE_VALF 未定义

c++ - (Ogre3d/PhysX/C++) - 如何绘制调试可视化

swift - 在 Swift 中按下按钮时创建一个 if 语句

c++ - 如何通过引用推送 vector ?