【发布时间】:2012-12-13 22:23:03
【问题描述】:
我正在制作一个非常简单的程序,只是一个小聊天机器人 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 的东西?我真的很困惑,希望能得到一些关于如何改进这个程序以使其真正发挥作用的建议。
【问题讨论】:
-
一方面,您永远不会调用您的 init() 方法,因此字典永远不会被初始化。
-
听起来你没有通过调试器运行。您应该运行调试器,因为它会因异常而中断,您可以找出它崩溃的确切原因。
-
高级 STL 和对 STL 完全无知的完美结合。我很感兴趣。查看如何使用
std::map和std::vector,这将使这段代码更容易,更不容易出错。 -
我建议你下载Visual C++,它的调试器要好得多
-
在关键字结构的定义中,您将响应定义为长度为零的字符串数组。这肯定不是你想要的?
标签: c++ pointers artificial-intelligence chatbot