简体   繁体   English

简单聊天机器人的分段错误(核心转储)

[英]Segmentation fault (core dumped) for simple chatbot

I'm having trouble with a simple chatbot. 我在使用简单的聊天机器人时遇到了麻烦。 After I write 9 messages it says 我写了9条消息之后说

Segmentation fault (core dumped)

My code is 我的代码是

#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 聊天机器人消息的图片

I want the messaging to continue indefinitely I've looked everywhere and can't find a solution to this problem. 我希望消息传递无限期地继续我到处寻找并找不到解决这个问题的方法。 Any help would be appreciated. 任何帮助,将不胜感激。

You are getting outside the responses vector range. 你越过响应向量范围。 There are 4 responses, this means their indicies are in range from 0 to 3. rand() % 5 would return values in range from 0 to 4. When nSelection is equal to 4, you are trying to access element which is after the last in vector. 有4个响应,这意味着它们的指示范围从0到3. rand() % 5将返回0到4范围内的值。当nSelection等于4时,您试图访问最后一个的元素在向量中。

As a possible solution you can get response index like rand() % Responses.size() , then you will never get out of bounds. 作为一种可能的解决方案,您可以获得响应索引,如rand() % Responses.size() ,那么您将永远不会超出范围。 The situation when Responses is empty should be handled separately, to prevent dividing by zero. 响应为空时的情况应单独处理,以防止除以零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM