如何逐个字符地从文件读取到2D数组

时间:2018-02-22 20:35:07

标签: c++ arrays

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

3
3
-x-
xx-
--x

我能够使用单独的函数读取前两个整数,但是当我使用此方法复制它时,我得到一个全0的3x6 2d数组。输出是

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

1 个答案:

答案 0 :(得分:1)

要从文件中逐字逐句阅读,您有一些选择。

角色扮演

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

相关问题