我在使用简单的聊天机器人时遇到了麻烦。我写了9条消息后说
Segmentation fault (core dumped)
我的代码是
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <ctime>
using namespace std;
const string user_template = "USER: ";
const string bot_template = "Bot: ";
int main(){
vector<string> Greeting{
"Hi!",
"Hey",
"Hello",
"What's up?",
"What's good?"
};
vector<string> Responses{
"Fine, thanks",
"Good, thanks",
"I'm OK",
"Everything is good"
};
//srand((unsigned) time(NULL));
string sResponse = "";
string tResponse = "";
while(cin){
string user_msg;
cout << user_template;
std::getline (std::cin, user_msg);
int nSelection = rand() % 5;
sResponse = Greeting[nSelection];
tResponse = Responses[nSelection];
if(user_msg == "quit"){
break;
}
else if(user_msg == "How are you?"){
cout << bot_template << tResponse << endl;
}
else{
cout << bot_template << sResponse << endl;
}
}
}
Picture of chatbot message
我希望该消息无限期地继续发送,我到处都是,并且找不到解决该问题的方法。任何帮助,将不胜感激。
最佳答案
您超出了响应 vector 范围。有4个响应,这意味着它们的索引范围是0到3。rand() % 5
返回的值范围是0到4。当nSelection等于4时,您正尝试访问 vector 中最后一个元素之后的元素。
作为一种可能的解决方案,您可以获得rand() % Responses.size()
之类的响应索引,那么您将永远不会超出范围。响应为空的情况应分开处理,以防止被零除。