首页 > 解决方案 > 如何创建具有空值和递减编号系统的二维数组网格以及来自 .txt 文件的输入值?

问题描述

我的任务是编写具有规范的网格,并在多维数组中插入来自示例 .txt 文件的一些数据。

在将示例数据放入其中之前,我无法自行创建网格。

对于第一行,我使用 for 循环打印出第一行十六进制。最底部的 for 循环打印出最后一行十六进制。所以从技术上讲,第一行和最后一行十六进制之间的二维数组是 9 行乘 12 列的二维数组。我已经注意到了,但我只是想看看它现在是否有效,for稍后我将更改循环中的值。

对于最后一行,我不确定如何打印水平 0 - 8,它从第 3 个元素到第 11 个元素的最后一行十六进制下方开始。

该网格应该用于显示 .txt 文件中给出的一些信息。我只是在测试是否可以将 .txt 文件中的值存储到 2D 数组中,如图所示,然后输出给定的值。

Sample .txt file: 
  [1, 1]-3-Big_City[1, 2]-3-Big_City[1, 3]-3-Big_City[2, 1]-3-Big_City
  [2, 2]-3-Big_City[2, 3]-3-Big_City[2, 7]-2-Mid_City[2, 8]-2-Mid_City
  [3, 1]-3-Big_City[3, 2]-3-Big_City[3, 3]-3-Big_City[3, 7]-2-Mid_City
  [3, 8]-2-Mid_City[7, 7]-1-Small_City

文本文件中的坐标表示从水平轴读取的 X 和 Y 轴,然后是垂直轴。

文本文件中的信息由分隔符“-”分隔。[1,1]表示第二列中'3'(cityID)的值的坐标,而第三列是城市名称。但就目前而言,预期的输出只是 .txt 文件中所述坐标处每个“-”间距的单个数字。

我知道我的示例代码目前还没有从 .txt 文件中打印任何内容。因为如果我要打印出字符串内容,那将是 .txt 文件中的所有内容。我正在考虑使用向量/字符串流并添加一个分隔符来忽略“-”。

ifstream fileName;
fileName.open("citylocation.txt");
string content;
getline(fileName, content); //this will read the file line by line

const int GridX = 12, GridY = 12;
int cityMap[GridX][GridY];

cout << " ";
for (int i = 0; i < 12; i++) //printing out the hexes on first row
    cout << " # ";
cout << endl;

for (int i = 1; i <=8; i++)
{
    cout << 8-i << " "; //printing out the number at side
    for (int j = 1; j < 12; j++)
    {

        cout << "  ";
    }
    cout << endl;
}

cout << " ";
for (int i = 0; i < 11; i++) //printing out the hexes on last row
    cout << " # ";
cout << endl;

预期成绩:

   # # # # # # # # # # #
 8 #     2 2           #
 7 #     2 2       1   #
 6 #                   #
 5 #                   #
 4 #                   #
 3 #   3 3 3           #
 2 #   3 3 3           #
 1 #   3 3 3           #
 0 #                   #
   # # # # # # # # # # #
     0 1 2 3 4 5 6 7 8

实际输出:

     #  #  #  #  #  #  #  #  #  #  #  #
  8
  7
  6
  5
  4
  3
  2
  1
  0
    #  #  #  #  #  #  #  #  #  #  #

标签: c++multidimensional-array

解决方案


除了是否需要数字或空格的问题,需要使用增加的数字序列来减少数字序列,中间有这个:

for (int i = 1; i < 12; i++)
{
    cout << i << " "; //printing out the number at side
    // other stuff in between using i
    cout << endl;
}

给出数字 1, 2, 3, .... 11。

值得注意的是,12 - i对于这些中的每一个,都给出 11、10、9、... 1。减号 i 使其减少而不是增加。

(这并不是你最终需要的,因为边缘,在你的代码中,一些循环到 11 和一些循环到 12 暗示了这些边缘)。

for (int i = 1; i < 12; i++)
{
    cout << 12 - i << " "; //printing out decreasing numbers at side
    // other stuff in between using i, which is unchanged
    cout << endl;
}

有 12 两次可能会使它变得不灵活 - 一个const数字可能值得考虑。


推荐阅读