c++ - 如何创建具有空值和递减编号系统的二维数组网格以及来自 .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
# # # # # # # # # # #
解决方案
除了是否需要数字或空格的问题,需要使用增加的数字序列来减少数字序列,中间有这个:
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
数字可能值得考虑。
推荐阅读
- python - Pandas 数据框仅在 for 循环中保留最后一个值
- bazel - 如何找到由 bazel 目标生成的可执行文件
- node.js - 我需要创建一个网页并创建一个名为重要或否的复选框
- django - ModuleNotFoundError:没有名为“__main__.models”的模块;从数据库导入模型时,'__main__' 不是包
- php - PHP SameSite 会话问题,会话不起作用
- google-apps-script - 您可以使用 Google Script 在特定时间为未来日期创建日历事件吗?
- java - Spring Boot Security OAuth2 自定义异常消息
- ios - 推送通知不起作用 Xcode 11.3.1
- c - 包含状态机的文档 C 代码
- angular - 使用 ngx-bootstrap 时 Angular 9 抛出错误