繁体   English   中英

如何逐个字符地从文件读取到二维数组

[英]How to read character by character from a file to a 2D array

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

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

按文本行
从您的输入数据示例中,您可能希望改为读取文本行:

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 的输入文件。

暂无
暂无

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

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