【问题标题】:Reading characters including white spaces and excluding newlines from file c++从文件 c++ 中读取包括空格和排除换行符的字符
【发布时间】:2012-11-11 04:47:12
【问题描述】:

正如标题所示,我想读取文件中的每个字符,包括空格和不包括新行。

文件外观示例。

     .       
##         . :
   #___-     
##
--------------
______________

然后我使用映射将每个字符转换为整数。

地图std::map<char, int> map_converter;

std::ifstream map("level_1.map");

for( int t = 0; t < TOTAL_TILES; t++ ) {
    int tileType = -1;
    char load_type = ' ';

    map >> load_type;
    tileType = map_converter.find(load_type)->second;
    tiles[t] = new Tile(x, y, tileType);
}

当我编译它时,我只得到一个`Segmentation fault (core dumped)

我该怎么做? `

【问题讨论】:

  • if (map_converter.find(load_type) == map_converter.end()) 我们会遇到问题。在结束迭代器上调用second 无效。
  • 嗯,我不明白你的意思。我对 C++ 相当陌生。我应该如何解决这个问题?
  • @DanAndreasson 我会回答的。

标签: c++ file map char


【解决方案1】:

如果std::map::find 找不到值,它将返回std::map::end。问题在于分配 tileType = std::map::end()-&gt;second 无效。

std::ifstream map("level_1.map");

for( int t = 0; t < TOTAL_TILES; t++ ) {
    int tileType = -1;
    char load_type = ' ';

    map >> std::noskipws >> load_type;

    if (map_converter.find(load_type) == map_converter.end()) {
        continue;
    }
    tileType = map_converter.find(load_type)->second; //this is now safe to do.
    tiles[t] = new Tile(x, y, tileType);
}

【讨论】:

  • 但是还有一个问题,怎么不跳过空格?
  • @DanAndreasson 为您的信息流设置noskipws(map &gt;&gt; std::noskipws;)
  • 嗯。当我使用 noskipws 时,我再次收到分段错误错误。
  • @DanAndreasson 是在同一个地方的段错误,你能发布你得到段错误的代码行吗?
猜你喜欢
  • 2010-09-12
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-23
  • 2018-05-24
  • 2014-06-03
相关资源
最近更新 更多