2016-12-02 152 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'全部应该是! –

相关问题