C++中的数组出错
Error with arrays in C++
问题是我想要'o',而不是重复。。。我试着找,但失败了!还要向我解释这是怎么发生的。我是一个新的学习程序员!
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
using namespace std;
int main()
{
//all in-game variables here
string o = "o";
int oH = 0;
int oW = 0;
//variables ending point...
bool run = true;
bool frameShow = true;
char input;
int width = 53;
int height = 22;
string px[width][height];
while (run)
{
for (int xEmp=0; xEmp<height; xEmp++){
for (int yEmp=0; yEmp<width; yEmp++)
{
px[xEmp][yEmp]= " ";
}
if (frameShow)
{
clrscr(); // Must be at start
px[oH][oW] = o;
for (int x=0; x<height; x++)
{
for (int y=0; y<width; y++)
{
cout << px[x][y];
}
cout << "n";
frameShow = false; // Must be at end
}
}
if (kbhit())
{
input = getch();
// Most Used ones are:
// char 119 for "w"
// char 97 for "a"
// char 115 for "s"
// char 100 for "d"
// char 32 for "space"
// char 27 for ESC
if (input == 119)
{
oH--;
frameShow = true;
}
else if (input == 115)
{
oH++;
frameShow = true;
}
else if (input == 97)
{
oW--;
frameShow = true;
}
else if (input == 100)
{
oW++;
frameShow = true;
}
else if (input == 27)
{
// Game exits...
// To terminate, use:
run = false;
}
if(oH > height)
{
oH = height;
}
else if(oH < 0)
{
oH = 0;
}
if(oW > width - 1)
{
oW = width - 1;
}
else if(oW < 0)
{
oW = 0;
}
}
}
}
// Output for confiming program termination
clrscr();
cout << "n - Terminated! - n";
return 0;
}
首先,width
和height
的使用正在更改。px[width][height];
、px[xEmp][yEmp]
、xEmp<height
、yEmp<width
。一次您将其用作px[width][height];
,然后使用px[height][width];
。保持代码的连贯性!
if(oH > height) { oH = height; }
也是错误的。身高减去一。
这可能也不会达到你想要的效果:
for (int x=0; x<height; x++)
for (int y=0; y<width; y++)
{
cout << px[x][y];
}
cout << "n";
正确使用括号,如果你不知道如何使用,请始终使用括号!
同样,我认为你没有正确使用括号:
for (int xEmp=0; xEmp<height; xEmp++){
for (int yEmp=0; yEmp<width; yEmp++)
{
px[xEmp][yEmp]= " ";
}
... // do other things
}
我想你想马上关闭它,把一切都放回太空,让他们做其他工作。现在,它将把一行设置回空格,打印所有内容并运行代码,并且只在下一行为空之后。
for (int xEmp=0; xEmp<height; xEmp++){
for (int yEmp=0; yEmp<width; yEmp++)
{
px[xEmp][yEmp]= " ";
}
}
... // do other things
Ps:clrscr()
是一个非标准的功能,只适用于Windows,我认为对于Linux使用system('clr');
Ps2:如果只存储字符,为什么要使用std::string
而不是字符?
相关文章:
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 将链表转换为指针数组时出错
- 为 NewObjectA() 函数创建 jvalues 的参数数组时出错 - JNI Invocation API
- 基于数组的列表 - 动态数组创建时出错
- 从斐波那契序列 c++ 中的数组中查找正确的元素时出错
- 分段 使用 MPI_Gather 收集字符数组时出错
- 读取字符串字符时出错 - 对于数组中的字符串值
- 声明数组>> int arr[] 时出错;在C++(虽然在 Java 中有效)?
- 在 c++ 中返回一维数组时出错
- 将 2D 数组传递给 C++ 中的函数时出错
- 在 c++ 上创建动态数组时出错
- 尝试返回指向 Visual Studio 中的动态数组的指针时出错C++
- 将 find_if() 与数组一起使用的代码段中出错
- 在比较特定输入中的程序的数组中出错
- 分段 填充数组时出错
- 数组作为函数参数查找数组长度时出错
- 读取结构数组时出错
- 将数组指针传递到函数时出错
- C++将指针数组传递给函数指针数组时出错
- 在数组中插入数据时出错 - 数组下标'int[int]'的类型无效