每次从文件中读取一个字符(c++)并存储到2D数组中

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

本文关键字:c++ 数组 2D 字符 存储 文件 读取 一个      更新时间:2023-10-16

所以我在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 

前两个数字表示网格的大小。我试图读取每个字符(忽略初始数字)并将字符存储到称为网格的数组中。任何建议吗?

我在stackoverflow上发现了其他类似的问题,但没有一个与此背景相同,也没有一个给我一个明确的答案。我只是想一次从文件中读取一个字符,并将该字符存储到2D数组中,以便数组中的每个字母都可以轻松引用。有人能帮帮我吗?

我相信你在找这样的东西吧?

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

我首先取前两个数字,并将它们命名为列和行。然后在两个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