如何按字符从文件到2D数组读取字符

How to read character by character from a file to a 2D array

本文关键字:字符 2D 数组 读取 文件 何按      更新时间:2023-10-16

我正在尝试从看起来像这样的文本文件中读取字符。" - "应该转换为零,而" x"应该转换为零

3
3
-x-
xx-
--x

我能够使用单独的函数读取前两个整数,但是当我使用此方法复制它时,我将获得一个带有所有零的3x6 2D数组。输出为

0 0 0
0 0 0 
0 0 0 
0 0 0
0 0 0

要从文件中读取字符,您有一些选项。

字符

char c;
ifstream data_file("my_file.txt");
while (data_file >> c)
{
  Do_Something_With_Character(c);
}

by text Line
从输入数据示例中,您可能需要读取文本行:

std::string text;
ifstream data_file("my_file.txt")
while (getline(data_file, text))
{
  for (int index = 0; index < text.length(); ++i)
  {
    Do_Something_With_Character(text[index]);
  }
}

注意:以上示例是读取数据的通用。他们不解析OP的输入文件。