为什么我的程序在运行这个特定的函数后会崩溃
Why does my program crash after running this particular function?
每当我在程序中键入运行此函数的命令时,它就会运行,然后崩溃,说:
"应用程序已请求运行时以异常方式终止它。">
它为什么要这样做?
void showInventory(player& obj) {
std::cout << "nINVENTORY:n";
for(int i = 0; i < 20; i++) {
std::cout << obj.getItem(i);
i++;
std::cout << "ttt" << obj.getItem(i) << "n";
}
}
std::string getItem(int i) {
return inventory[i];
}
在此代码中:
std::string toDo(player& obj) //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "nWhat do you wish to do?n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return NULL;
}
else if(ans == commands[1]) {
showInventory(obj);
return NULL;
}
}
需要:
std::string toDo(player& obj) //BY KEATON
{
std::string commands[5] = // This is the valid list of commands.
{"help", "inv"};
std::string ans;
std::cout << "nWhat do you wish to do?n>> ";
std::cin >> ans;
if(ans == commands[0]) {
helpMenu();
return "";
}
else if(ans == commands[1]) {
showInventory(obj);
return ""; // Needs to be '""'
}
}
归功于原型斯塔克!
当i=19时,您得到数组中的最后一个项,在此之后i变为20,并且还有另一个getItem,它应该会导致越界异常
for(int i = 0; i < 20; i++) {
std::cout << obj.getItem(i);
这不是很正确。不要使用幻数。使用int listSize=obj.listSize()(将由您实现)而不是20
listSize = obj.ListSize();
for(int i = 0; i <listSize ; i++) {
std::cout << obj.getItem(i);
通过这种方式,你将确保你没有超出范围。
此外,如果你想在一个循环中打印两个项目(我不知道为什么),你可以这样做:
void showInventory(player& obj) { // By Johnny :D
std::cout << "nINVENTORY:n";
int listSize = obj.ListSize()/2; //if you are sure that is odd number
for(int i = 0; i < listSize; ++i) {
std::cout << obj.getItem(i);
i++;
std::cout << "ttt" + obj.getItem(i) + "n";
}
}
编写一个函数:
class player{
public:
//--whatever it defines
int ListSize()
{
return (sizeof(inventory)/sizeof(inventory[0]));
}
};
然后使用
void showInventory(player& obj) { // By Johnny :D
int length = obj.ListSize();
std::cout << "nINVENTORY:n";
for(int i = 0; i < length; i++) {
std::cout << obj.getItem(i);
i++;
std::cout << "ttt" << obj.getItem(i) << "n";
}
}
相关文章:
- 内联映射初始化的动态atexit析构函数崩溃
- C++设置器函数崩溃
- 在C++中删除指针数组时析构函数崩溃
- 使用向量的函数崩溃,调试器说访问冲突读取位置
- 分配内存并在回调时调用C++的 Rust 函数崩溃
- MEX文件实现特征库伪内函数崩溃
- C :复制构造函数崩溃
- 创建'new'实例可以解决析构函数崩溃问题?
- wglCreateContextAttribsARB函数崩溃
- OpenCV 均值函数崩溃,掩码从 OpenCV 阈值函数创建
- 使用Armadillo类型的lambda函数崩溃的未知原因
- 空析构函数崩溃程序:C++
- avformat_open_input函数崩溃
- boost::任何析构函数崩溃
- VS CTP 14的std::线程析构函数崩溃
- 使用std::enable_shared_from_this时,析构函数崩溃
- C++继承虚拟函数崩溃
- 分配空终止符时Windows剪贴板函数崩溃
- 从函数崩溃返回,仅在代码中的某个点之后
- 模板函数崩溃