[英]2 Dimensional Char Array C++
Is there such a way to initialize a char array and then loop through them all and change the value? 有没有一种方法可以初始化一个char数组,然后遍历它们并更改值? I'm trying to create a table like structure. 我正在尝试创建类似结构的表格。
I just keep getting errors like "Cannot initialize a value of type 'char' with an lvalue of type 'const char [3]'. 我只是不断收到类似“无法用'const char [3]类型的左值初始化'char'类型的值之类的错误。
I'm using Xcode 6.1.1 for development 我正在使用Xcode 6.1.1进行开发
int width = 25;
int height = 50;
char board [50][25] = {""}; // height x width
for (int i = 0; i < width; i++) {
for (int j = 0; i < height; i++) {
if (i == 0) {
board[i][j] = {"||"};
}
}
}
The problem is with board[i][j] = {"||"};
问题出在board[i][j] = {"||"};
. 。 The string "||"
字符串"||"
cannot be implicitly converted to a single character. 不能隐式转换为单个字符。
It's not clear what you are trying to do; 目前尚不清楚您要做什么。 each cell of the board is a char
, and ||
董事会的每个单元格都是一个char
,而||
is two chars. 是两个字符。 Two doesn't go into one. 二不合一。 Perhaps you meant: 也许您的意思是:
board[i][j] = '|';
Also, your loop nesting is backwards (the height
loop should be the outer one). 另外,循环嵌套是向后的( height
循环应位于外部)。 The indexing of an array is the same as its declaration, so for board[i][j]
to work when the declaration was char board[50][25]
, i
must be ranging from 0
to 49
. 数组的索引与其声明相同,因此要使board[i][j]
在声明为char board[50][25]
时起作用, i
范围必须为0
到49
。
An improvement would be: 一个改进将是:
int const width = 25;
int const height = 50;
char board[height][width] = {};
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++)
Set the characters in the array with single quotes, not double. 用单引号而不是双引号设置数组中的字符。 So: 所以:
board[i][j] = '|';
Also, notice that you can only put a single character in each position 另外,请注意,您只能在每个位置放置一个字符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.