首页 > 解决方案 > 我的功能不会取代“。” 使用“”,它不会按应有的方式显示数组

问题描述

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

我只是想在屏幕上显示一个空白字段,并能够使用 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:

    |................................................|

标签: c++

解决方案


问题是这样的:

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), '.', ' ');

推荐阅读