一次从文件中读取一个字符(C++)并存储到二维数组中?

Reading characters from a file one at a time (C++) and storing to a 2D array?

所以我在用 C++ 读取文本文件时遇到了一些问题。我想要做的是从包含字母网格的文本文件中读取。这是我设置的内容:

int main()
{
    char grid[10][10];
    ifstream input;
    input.open("puzzle1_size10.txt");

    //what goes here

    input.close();
    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
            cout<< grid[i][j]<<" ";
        cout<<endl;
    }
}

文本文件是这样的:

10 10
f e h l o a k r a y 
e s r r t s c d o y 
a l u g d o e e g a 
t c y y m h l j y a 
u r a p s y n a r j 
r e u d c a e p e r 
e t s o c h t p h c 
e g o p e h w l t w 
h h c l s d o e c a 
l n h c a m r l e e 

前两个数字代表网格的大小。我正在尝试读取每个字符(忽略初始数字)并将字符存储到名为 grid 的数组中。有什么建议吗?

我在 Whosebug 上发现了其他类似的问题,但 none 与此具有相同的上下文,其中 none 给了我一个明确的答案。我只是试图一次从文件中读取一个字符并将该字符存储到二维数组中,以便可以轻松引用数组中的每个字母。有人可以帮忙吗?

我相信您正在寻找这样的东西?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char grid[10][10];
    ifstream input;
    input.open("File.txt", ios::in);

    int column = 0;
    int row = 0;


    input >> column >> row;

    for (int column_counter = 0; column_counter < column; column_counter++){

        for (int row_counter = 0; row_counter < row; row_counter++){

            input >> grid[column_counter][row_counter];

        }
    }



    input.close();
    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
            cout<< grid[i][j]<<" " << endl;
        cout<<endl;
    }
}

我先取了前两个数字,分别命名为column和row。然后在两个 for 循环中,我添加了计数器来计算网格的位置,直到它们达到您在文件开头指定的位置。

有什么问题尽管问!我会尽快给他们添加评论。我现在在一家咖啡馆里。

因为这是标记 c++,我建议你使用 std::vector 而不是普通数组,这样你就有了更灵活的方法

std::string line;
getline(file, line); // skip first line
std::vector<std::vector<char>> grid;
while(getline(file, line))
{
    std::vector<char> insideV (line.begin(), line.end()); // read string into vector of char
    grid.push_back(insideV);
}

......
std::cout << grid[0][0]; // f