繁体   English   中英

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

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

我创建了一个代码,将我的数组输出到二维网格中,例如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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM