我的问题是我定义了这样一个字符串:
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::istringstream
和 std::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/