【发布时间】:2016-05-06 12:56:51
【问题描述】:
我正在尝试获取文本文件的值并将其加载到二维数组中。我遇到的问题是 char 变量的值似乎只覆盖了每个空白位置,我不知道为什么。
所以我打开了文件,我可以访问它来读取它的内容或在屏幕上显示它们,然后像这样设置我的二维数组:
char chessBoards[BOARD_SIZE - 1][BOARD_SIZE - 1] = {{'A'}}; // All elements of 2D array initialized
int x = 0; // line position - which line we are looking at
int y = 0; // row position - which row we are looking at
在这个测试中,输出是所有 C 字符和一个 D 字符,我后来告诉它是这样的,所以我的问题似乎是文本文件的位置没有被复制到 char 变量中。
file.open(games);
char point = 'Z';
while (file.get(point))
{
for (int x = 0; x < BOARD_SIZE; x++)
{
for (int y = 0; y < BOARD_SIZE; y++)
{
chessBoards[x][y] = point;
}
}
}
chessBoards[1][1] = 'D';
cout << chessBoards[1][1];
for (int x = 0; x < BOARD_SIZE; x++)
{
for (int y = 0; y < BOARD_SIZE; y++)
{
cout << "chessBoards[" << x << "][" << y << "]: ";
cout << chessBoards[x][y] << endl;
}
}
但在这个变体中,除了一个“D”之外,每个值都是空白的
file.open(games);
char point = 'Z';
while (file.get(point))
{
for (int x = 0; x < BOARD_SIZE; x++)
{
for (int y = 0; y < BOARD_SIZE; y++)
{
chessBoards[x][y] = 'C';
}
}
}
cout << chessBoards[1][1];
for (int x = 0; x < BOARD_SIZE; x++)
{
for (int y = 0; y < BOARD_SIZE; y++)
{
cout << "chessBoards[" << x << "][" << y << "]: ";
cout << chessBoards[x][y] << endl;
}
}
这告诉我它没有正确地从文件中获取值,但是在这个版本中,在顶部显示文件的内容没有问题。但是,如果我尝试将其他东西放在同一区域,它只会覆盖数组的第一个位置并停止。
file.open(games);
char point = 'Z';
while (file.get(point))
{
for (int x = 0; x < BOARD_SIZE; x++)
{
for (int y = 0; y < BOARD_SIZE; y++)
{
chessBoards[x][y] = 'C';
}
}
chessBoards[x][y] = 'C';
chessBoards[x][y] = point;
cout << point;
}
chessBoards[1][1] = 'D';
cout << chessBoards[1][1];
【问题讨论】:
-
您在循环外声明的
x和y变量与嵌套fors 内声明的变量不同,它们的值保持0,所以在循环你基本上设置chessBoards[0][0] = point;。要实际读取文件,您应该将循环中的行更改为chessBoards[x][y] = point。然后监听 Paddy 并将数组声明为chessBoard[BOARD_SIZE][BOARD_SIZE]。
标签: c++ arrays multidimensional-array char