[英]Making a display board in console using c++
I am trying to make a display board that takes a char
and displays it in a specified location.我正在尝试制作一个带有
char
并将其显示在指定位置的显示板。 The following is the code showing what i did to "draw" the board.以下代码显示了我为“绘制”电路板所做的工作。
const int height = 3;
const int width = 10;
char board[width][height];
void draw()
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (!(x == 9))
{
cout << board[y][x];
}
else
{
cout << board[y][x] << endl;
}
}
}
}
Now, if i create a function to fill the array with 'a' to test it and call draw()
, it runs fine and this is the result i get现在,如果我创建一个函数来用 'a' 填充数组来测试它并调用
draw()
,它运行良好,这就是我得到的结果
aaaaaaaaaa
aaaaaaaaaa
aaaaaaaaaa
The fill array function:填充数组函数:
void fillarray()
{
for (int a = 0; a < height; a++)
{
for (int b = 0; b < width; b++)
{
board[a][b] = 'a';
}
}
}
However, if i try to specify a location using the following function, the result is a mess但是,如果我尝试使用以下函数指定位置,结果是一团糟
void write(char c, int x, int y)
{
board[y][x] = c;
}
How i called write()
我如何调用
write()
write('a', 1, 1);
So i must be doing something wrong in the write
function but i cant figure out what since i am kinda new to c++.所以我一定在
write
函数中做错了什么,但我无法弄清楚是什么,因为我对 C++ 有点陌生。 Also thanks in advance for helping.也提前感谢您的帮助。
Edit: Felt like it would help if i included the result i get when i call write()
编辑:感觉如果我包含调用
write()
时得到的结果会有所帮助
a
a
Your board is declared as:您的董事会声明为:
char board[width][height];
But you are writing to the board array like this:但是您正在像这样写入板阵列:
cout << board[y][x];
Where "y" is your height variable and "x" is your width variable.其中“y”是您的高度变量,“x”是您的宽度变量。 I think you have your index variables for the 2-d array reversed.
我认为您将二维数组的索引变量颠倒了。 Don't your really mean say.
不要你真的刻薄说。
cout << board[x][y];
All your assignment statements in your other functions have the same bug.其他函数中的所有赋值语句都有相同的错误。
Or better yet, so you don't have to fix all your code, just declare board as:或者更好,因此您不必修复所有代码,只需将 board 声明为:
char board[height][width];
Also, some code style changes to improve your code.此外,还更改了一些代码样式以改进您的代码。
Instead of this:取而代之的是:
for (int x = 0; x < width; x++)
{
if (!(x == 9))
{
cout << board[y][x];
}
else
{
cout << board[y][x] << endl;
}
}
This:这个:
for (int x = 0; x < width; x++)
{
cout << board[y][x];
}
cout << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.