0

我正在制作一个非常简单的程序,只是一个小聊天机器人 AI 之类的东西,而且我有一些代码,当然是 c++ 用于该程序。我没有收到任何错误,但是当我运行它时会出现一个窗口,说 program.exe 已停止工作,就像它停止响应一样。我的代码是:

#include<iostream>
#include<string.h>
#include<cmath>
#include<vector>
#include<ctime>
#include<conio.h>
#include<algorithm>
#include<cstdlib>
using namespace std;

struct strarray{
   char* array[];
};

struct keyword{
   string keywords;
   string responses[];       
};


keyword * dictionary = new keyword[2];
keyword defaultr;

keyword getMatch(string key);
string sconvert(string con);
void init();
string getResp(keyword key);

bool cont=true;

int main(int argc, char* argv[]){
   string input;
   while(cont){
            getline(cin,input);
            cout << getResp(getMatch(input));
            getch();
            getch();
   }
}

string sconvert(string con){
   con.erase(remove_if(con.begin(), con.end(), ::isspace), con.end());
   con.erase(remove_if(con.begin(), con.end(), ::ispunct), con.end());
   return con;
}

void init(){
   srand(time(NULL));
   dictionary[0].keywords="hello";
   dictionary[0].responses[0]="Hello, how have you been?";
   dictionary[0].responses[1]="Hello, have you missed me?";
   dictionary[0].responses[2]="Hey, how's it going?";
   defaultr.responses[0]="That's interesting, tell me more.";
   defaultr.responses[1]="Please, tell me more.";
}

keyword getMatch(string key){
    for(int i=0; i<sizeof(dictionary); i++){
            if(key==dictionary[i].keywords){return dictionary[i];}
    }
    return defaultr;
}

string getResp(keyword key){
   return key.responses[rand() % sizeof(key)];
}

当我运行它时,它会正常打开,但是当我输入一些内容后,它会“停止工作”。有人可以告诉我我需要改变什么,为什么会受到赞赏。

有指针问题吗?还是有什么rand?我真的很困惑,希望能得到一些关于如何改进这个程序以便它真正起作用的建议。

4

2 回答 2

2

sizeof(dictionary)将给出sizeof(keyword*), 可能48, 因此您将遍历字典数组的末尾并终止。

最简单的解决方法:定义一个常量来存储数组长度。

const dictionarySize = 2;

并始终使用它。

您还需要更改struct keyword为:

struct keyword{
   string keywords;
   string responses[3];       
};
于 2012-12-13T22:44:06.740 回答
1

首先你有一个无限循环,所以程序应该永远工作..我看了一眼代码,使用 rand() % sizeof(key) 是错误的,响应不是预先确定的,所以你要么将它设置为特定的例如值

struct keyword {
    string keywords;
    string responses[2];       
};
rand() % sizeof(key.responses)

或者你让你的结构像这样

struct keyword {
    string keywords;
    vector<string> responses;      
};
rand() % key.responses.size()
//After setting the responses by push_back for example

还有其他方法,但这更安全,不需要内存管理......

于 2012-12-13T22:37:12.513 回答