我正在做一个绞刑游戏,并且遇到了这个问题。
Thread 1 stopped C:\Users........... Fault Access Violation at 0x4041e6: write of address 0x1a0000当我运行我的程序时,我得到了上面的错误,请您帮助我,告诉我代码的问题在哪里?
在代码中,a是player类的一个对象,它有一个函数retdifficulty(),它返回一个包含player.easy选择的困难的字符串,中间和硬是包含每一行20行的文本文件。
int gen()
{
randomize();
int j = random(10);
int a[]={0,2,4,6,8,10,12,14,16,18};
return a[j];
}
/***********************************************
Function to get a word from file
***********************************************/
char *getword()
{
int j = gen();
string word;
string wordlist[20];
if (strcmpi(a.retdifficulty(),"easy")==0)
{
int x = 0;
ifstream fin("easy.txt");
while (fin>>word)
{
strcpy(wordlist[x],word);
x++;
}
return wordlist[j];
}
if (strcmpi(a.retdifficulty(),"medium")==0)
{
int x = 0;
ifstream fin2("medium.txt");
while (fin2>>word)
{
strcpy(wordlist[x],word);
x++;
}
return wordlist[j];
}
if (strcmpi(a.retdifficulty(),"hard")==0)
{
int x = 0;
ifstream fin3("hard.txt");
while (fin3>>word)
{
strcpy(wordlist[x],word);
x++;
}
return wordlist[j];
}发布于 2015-08-27 17:50:12
试试下面的代码(记得添加#include<vector>)
int gen()
{
randomize();
return random(10) * 2;
}
/***********************************************
Function to get a word from file
***********************************************/
string getword() {
int j = gen();
string word, fname = "easy.txt";
vector<string> wordlist;
ifstream fin;
if (strcmpi(a.retdifficulty(),"medium")==0)
fname = "medium.txt";
else if (strcmpi(a.retdifficulty(),"hard")==0)
fname = "hard.txt";
fin.open(fname);
while (fin>>word)
wordlist.push_back(word);
return wordlist[j];
}发布于 2015-08-27 20:14:18
这个代码片段中可能的死亡点是:
while (fin>>word)
{
strcpy(wordlist[x],word);
x++;
}看起来很好,除了两件事:
string word;
string wordlist[20];和
char *strcpy(char *dest, const char *src);将string输入需要char *的函数应该会生成编译器警告,即使在1997年也是如此。
我的第一个倾向是使用std::string的赋值操作符来执行副本。
while (fin>>word)
{
wordlist[x] = word;
x++;
}它应该能工作,但我不能保证这一点在预标准化编译器中。
关于数组的脆性的其他常见注释仍然有效,但标准是“使用std::vector”。建议是有问题的,因为当时没有std::载体。没有标准。
因此,第一个建议是升级编译器并开始使用C++,而不是它的祖先。
如果这是一项工具链的作业,是由一名设法错过了过去20年的讲师强加在作业上的,那么,如果让傻瓜妨碍学生的学习,如果不是完全的话,那就让他们感到羞愧。如果你要教一门语言,那就教它。
除非这是编程史课程。
https://stackoverflow.com/questions/32255989
复制相似问题