我的函数不会用" "替换".",也不会按预期显示数组
my function does not replace "." with " " and it does not display the array as it should
我正在尝试显示从文件中检索到的二维数组,但它无法正确显示它。它也不会在将文件读入 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), '.', ' ');
相关文章:
- 显示错误输出的简单数组排序程序
- 显示数组中的学生 ID 和最高分
- 代码使用向量成功运行,但使用数组显示错误
- 对象初始化后在C++中显示 char 数组时的异常行为
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 在命令行上将输入显示到数组中时如何删除 ./a.out?
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- 如何在函数中显示结构数组
- 显示结构数组
- 在数组中显示第一个元素用户输入
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 我编写了一个程序来显示数组的内容,但它显示的是它的地址
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 将 5 个 for 循环压缩为,将数组显示为 1
- 为什么析构函数和复制构造函数使用对象数组显示此行为
- 在VC2010中使用Char数组显示字符串时发生运行时错误
- 将数组显示为表格
- 从boost::p roperty_tree读取数组显示为空白
- c++错误数组显示
- 二维动态数组c++显示问题