C++ 简单聊天机器人的分段故障(堆芯转储)
我在一个简单的聊天机器人上遇到了麻烦。在我写了9条信息后,它说C++ 简单聊天机器人的分段故障(堆芯转储),c++,C++,我在一个简单的聊天机器人上遇到了麻烦。在我写了9条信息后,它说 Segmentation fault (core dumped) 我的代码是 #include <iostream> #include <map> #include <vector> #include <string> #include <ctime> using namespace std; const string user_template = "USER: "
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;
}
}
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
常量字符串user_template=“user:”;
常量字符串bot_template=“bot:”;
int main(){
矢量问候语{
“嗨!”,
“嘿”,
“你好”,
“怎么了?”,
“什么好?”
};
向量响应{
“很好,谢谢”,
“很好,谢谢”,
“我很好”,
“一切都很好”
};
//srand((无符号)时间(NULL));
字符串sResponse=“”;
字符串响应=”;
while(cin){
字符串用户\u msg;
cout您超出了响应向量范围。共有4个响应,这意味着它们的标记在0到3之间。rand()%5
将返回0到4之间的值。当nSelection等于4时,您尝试访问位于最后一个in向量之后的元素
作为一种可能的解决方案,您可以获得响应索引,如rand()%Responses.size()
,您将永远不会越界。响应为空的情况应单独处理,以防止被零除。尝试使用-g编译并在gdb中运行。看看您定义了多少响应。您知道如何让它无限期响应,而不管我定义了多少响应吗?请不要发布pi文本的结构。