c++ - 我的功能不会取代“。” 使用“”,它不会按应有的方式显示数组
问题描述
我试图显示从文件中检索到的二维数组,但它不会正确显示。在将文件读入二维数组后,它也不会立即将元素从句点切换到空格。
我只是想在屏幕上显示一个空白字段,并能够使用 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
数组是 type std::string
,整个字符串被读入xy[x][y]
,而不是单个字符。
你可能想要的是这样的:
private: char xy[20][50];
然后另一个变化是:
file >> xy[x][y];
if (xy[x][y] == '.')
{
xy[x][y] = ' ';
}
请注意——您可以先将整个内容读入数组,而无需检查字符是否为 a .
,最后使用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), '.', ' ');
推荐阅读
- javascript - 如何在 JavaScript 中对选项列表中的多个字段进行排序
- python - 遍历股票价格python的行和列
- javascript - 具有多个默认值的 Javascript Switch 语句
- matrix - octave 使用向量作为矩阵的列索引
- javascript - 如何为参考 SVG 背景设置动画
- python - 有没有办法在 Kivy 中制作自定义 TextInput?
- java - 如何使用厨师以编程方式更新 JAVA_HOME - JRE
- google-cloud-platform - 连接断开时,Google Cloud Platform 无法运行长时间运行的进程
- javascript - Async/Await 不等待响应,返回 Promise 对象
- osgi - 无法部署包含 ComponentFactory OSGi 声明性服务的 Karaf kar 文件