我的函数不会用" "替换".",也不会按预期显示数组

my function does not replace "." with " " and it does not display the array as it should

本文关键字:数组 显示 替换 函数 我的      更新时间:2023-10-16

我正在尝试显示从文件中检索到的二维数组,但它无法正确显示它。它也不会在将文件读入 2D 数组后立即将元素从句点切换到空格。

我只是想在屏幕上显示一个空白字段,并能够使用 getField 函数加载更多字段。

C++
class Field
{
private: string  xy[20][50];
public:
Field() {}
void getField(string name)
{
ifstream file;
file.open(name);
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 50; y++)
{//periods should be changed to spaces
file >> xy[x][y];
if (xy[x][y] == ".")
{
xy[x][y] = " ";
}
}
}
file.close();
}
//displaying field
void display()
{
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 50; y++)
{
cout << xy[x][y];
cout << endl;
}
}
}
};
int main()
{
Field field1;
field1.getField("field1.txt.txt");
field1.display();
system("pause");
}
`````````````````````````````````````````````````
the txt file is pretty much this 20 times:
|................................................|

问题是这样的:

private: string xy[20][50];

然后你这样做,期望每个字符都被读入数组的每个元素:

file >> xy[x][y];

问题是由于xy数组是std::string类型,整个字符串被读入xy[x][y],而不是单个字符。

你可能想要的是这个:

private: char xy[20][50];

那么另一个变化是这样的:

file >> xy[x][y];
if (xy[x][y] == '.')
{
xy[x][y] = ' ';
}

只是一个注释 - 您可以先将整个内容读入数组中,而无需检查字符是否为.,最后使用 std::replace 替换:

#include <algorithm>
//...read everything first
for (int x = 0; x < 20; x++)
{
for (int y = 0; y < 50; y++)
file >> xy[x][y];
}
// now replace 
std::replace(&xy[0][0], &xy[0][0] + sizeof(xy), '.', ' ');