C++2D网格数组,从文件中读取和插入数组值

C++ 2D grid array, reading and inserting array values from file

本文关键字:数组 读取 插入 文件 网格 C++2D      更新时间:2023-10-16

我创建了一个代码,它将我的数组输出到二维网格中,类似于x和y轴。目前的代码和输出:

代码:

char array[9][9];
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
array[i][j] = '0';
}
}
for (int i = 0; i < 9; i++)
{
cout << i << "  ";
for (int j = 0; j < 9; j++)
{
cout << array[i][j] << "  ";
}
cout << endl;
}
cout << "   ";
for (int i = 0; i < 9; i++)
cout << i << "  ";
cout << endl;

输出:

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

现在我有一个文件,里面装满了坐标,我想把它标记出来。问题是我如何标出所有坐标,比如在我所做的网格上,在所有标记的坐标上加一个"1"。首先,我已经声明了我的ifstream并设法读取了它的内容。现在我被卡住了如有帮助,不胜感激

这是文件内容:

[1, 1]
[1, 2]
[1, 3]
[2, 1]
[2, 2]
[2, 3]
[2, 7]
[2, 8]
[3, 1]
[3, 2]
[3, 3]
[3, 7]
[3, 8]
[7, 7]

ifstream有一个获取文件路径的构造函数。要从.txt文件中读取字符,您所要做的就是使用ifstream对象中的>>运算符作为输入变量。要检查您是否完成了读取,您可以简单地使用ifstream对象的.eof函数。

#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream file("/path/to/your/file/yourfile.txt"); // From the root directory (in linux)
size_t size = 9; // Make this program to be more dynamically
char array[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j] = '0';
}
}
int x, y;
char padding;
while (!file.eof()) // While there is somthing more in the file
{
file >> padding >> x >> padding >> y >> padding;
/*
read char '[', then 'x'(number), then ',', then 'y'(number), and finally ']'
*/
array[x][y] = '1'; // Place the mark
}
for (int i = 0; i < size; i++)
{
cout << i << "  ";
for (int j = 0; j < size; j++)
{
cout << array[i][j] << "  ";
}
cout << endl;
}
cout << "   ";
for (int i = 0; i < size; i++)
cout << i << "  ";
cout << endl;
return 0;
}