[英]Segmentation fault (core dumped) for simple chatbot
我在使用简单的聊天机器人时遇到了麻烦。 我写了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;
}
}
}
我希望消息传递无限期地继续我到处寻找并找不到解决这个问题的方法。 任何帮助,将不胜感激。
你越过响应向量范围。 有4个响应,这意味着它们的指示范围从0到3. rand() % 5
将返回0到4范围内的值。当nSelection等于4时,您试图访问最后一个的元素在向量中。
作为一种可能的解决方案,您可以获得响应索引,如rand() % Responses.size()
,那么您将永远不会超出范围。 响应为空时的情况应单独处理,以防止除以零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.