2012-12-13 110 views
0

我正在製作一個非常簡單的程序,只是一個小聊天機器人AI類的事情,當然,我還有一些代碼,當然,程序的C++。我沒有得到任何錯誤,但是當我運行它時出現一個窗口,說program.exe已停止工作,就像它停止響應。我的代碼是:C++程序已停止工作

#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什麼?我真的很困惑,並希望得到一些關於如何改善這個程序的建議,以便它實際工作。

+1

原因之一,你永遠不打電話給你的init()方法,因此字典永遠不會被初始化。 – ryanbwork

+2

這聽起來像你沒有運行調試器。你應該運行調試器,因爲它會破壞異常,你可以確切地知道它爲什麼會崩潰。 – evanmcdonnal

+4

什麼是先進的STL和完全無知的STL迷人的組合。我很無禮。看看如何使用'std :: map'和'std :: vector',這會使這段代碼變得容易很多,而且容易出錯。 –

回答

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 

還有其他的方式,但這樣做很安全,沒有內存管理需要...

+0

我把它改成了sizeof(key.responses),並且實現了無限循環,我故意這麼做了,稍後我會改變它。我添加了響應數組大小的定義,並且仍然出現分段錯誤。順便說一下,我編輯了一些東西,這絕對是在getmatch函數期間,wtf在這裏是錯誤的,有人告訴我。 – user1478209

+0

寫下你的新密碼..還有一件事情是初始化所有關鍵字 – Ibrahim

2

sizeof(dictionary)將給出sizeof(keyword*),可能48,因此您將遍歷字典數組的末尾並終止。

最簡單的修復:定義一個常量來存儲數組長度。

const dictionarySize = 2; 

並在整個使用。

你也需要改變struct keyword到:

struct keyword{ 
    string keywords; 
    string responses[3];  
}; 
+0

謝謝,您實際上提供了一些幫助,與其他人不同,只是批評我而沒有給我任何有用的東西。 – user1478209

+0

更好的是,使用std :: vector或知道其大小的其他容器,而不是數組。 –