2016-12-02 137 views
0
char* szWords[] = { "caralho", "porra" }; 
if (IsGoldGrade(pObj)) //Ignore, its ok. //Crashing after i added the 
{ 
    for (int x = 0; x < sizeof(szWords); x++) { 
     if (strstr((strlwr((char*)szWords[x])), szChat)) { 
      char szBuffer[256]; 
      sprintf(szBuffer, "You can't type %s", szWords[x]); 
      Announce(pObj, szBuffer); 
      memset(szBuffer, 0, 256); 
      return; 
     } 
    } 
} 

Idk,但我不能用它作爲「代碼」在stackoverflow上。爲什麼我的應用程序崩潰?我的代碼有什麼問題?

引擎收錄:http://pastebin.com/u8yit8Rw

PS:因爲使用IM的Visual Studio 2003

+1

至少告訴我們是什麼錯誤... – csmckelvey

+0

你好。我在我的遊戲服務器上使用。錯誤是,當這個函數執行時,我的遊戲崩潰了。 – Lcs

+1

Pastebin上的文件包含可能被堆棧溢出禁止的單詞。刪除這些單詞,你應該能夠將整個代碼粘貼到你的問題中。 –

回答

1

for循環條件是錯誤的,我不能使用StrStrI。你想迭代指向char的指針數組。
您的循環for (int x = 0; x < sizeof(szWords); x++)繼續,而x < sizeof(szWords)。但是sizeof(szWords)而不是數組長度。它只是說你的陣列在內存中佔用了多少字節。它依賴於系統,但是它是char指針大小的兩倍,所以可能是8或16個字節。你需要將這個大小除以數組元素的大小,然後你將得到正確的數組大小。

重寫你for循環是這樣的:

for (int x = 0; x < sizeof(szWords)/sizeof(szWords[0]); x++)

,或者如果你的編譯器支持基於範圍的C++ 11,你可以嘗試:

for (const char *word : szWords)

除此之外,如果你正在編寫C++代碼,你應該使用STL和其他C++特性。比如你的字符串數組應被聲明爲:

std::vector<std::string> words = { "caralho", "porra" };

或者如果你的編譯犯規支持C++ 11(當時真的改變它...)

std::vector<std::string> words; 
words.push_back("caralho"); 
words.push_back("porra"); 

for (std::size_t i = 0; i < words.size(); ++i) { 
    // since you are using C string functions you will need word as C string 
    const char *word = words[i].c_str(); 
    // do whatever you want with word 
} 

還要考慮現代閱讀編寫代碼之前的C++書。

+0

謝謝!我現在要測試它。 – Lcs

+0

你能爲我推薦一本現代C++書嗎?謝謝。 – Lcs

+0

你的代碼不起作用:( – Lcs

1

從它的外觀來看,這是一個函數,用於檢查用戶是否寫了禁止的單詞?

我會用char* szWords[]...替換爲std::vector<std::string>來存儲禁止的字,並使用std::find來查看輸入是否在該列表中。

#include <algorithm> 
#include <iostream> 
#include <string> 
#include <vector> 

std::vector<std::string> bannedWords{"hamster", "elderberries", "etcetera"}; 

bool isBanned(const std::string &str) { 
    return std::find(bannedWords.begin(), bannedWords.end(), str) != bannedWords.end(); 
} 

int main() { 
    std::cout << "Is 'wally' banned? " << isBanned("wally") << std::endl; 
    std::cout << "Is 'elderberries' banned? " << isBanned("elderberries") << std::endl; 
} 

更多有關std::findhere

Here's an online demo

+0

謝謝我的朋友。但即時通訊使用VS 2003和那doens 't允許我使用你的功能 – Lcs

+0

@Lcs啊 - 我忽略了這一點。對不起! –

+0

@Lcs現在嘗試 - 'auto'可能不是VS 2003兼容的,而是'string','vector'和'find'全部應該是! –

相關問題