如何创建具有空值和递减编号系统并从.txt文件输入值的2D阵列网格?

时间:2019-01-09 15:42:34

标签: c++ multidimensional-array

我被赋予一项任务,用规范对网格进行编码,并从多维数组中的示例.txt文件中插入一些数据。

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

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

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

该网格应该用于显示.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文件中的所有内容。我正在考虑使用vectors / stringstream并添加一个定界符以忽略'-'。

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
    #  #  #  #  #  #  #  #  #  #  #

1 个答案:

答案 0 :(得分:0)

除了需要数字还是空格的问题以外,还需要使用递增的数字序列来减少数字序列,您还需要解决以下问题:

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。 减去我会使它减少而不是增加。

(由于边缘的缘故,这最终并不一定就是您所需要的,在代码中某些循环会转到11,某些循环会提示到边缘)。

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数字可能值得考虑。