【问题标题】:getline crashing when coming across a newline遇到换行符时getline崩溃
【发布时间】:2018-05-04 17:01:17
【问题描述】:

我正在尝试从带有\n 结尾的txt 文件中读取一些信息。 但是,每当我越过一条空线时,就会出现段错误。但是我只是希望这条线被忽略。

代码:

std::ifstream config_file (config_);
string input_line;

while (std::getline(config_file, input_line))
  {
    if (??check for newline??)
      continue   
  }

到目前为止我尝试过: 将 getline 更改为这些参数:

    (config_file, input_line, '\n')

还有这个 if 语句:

if (input_line.at(0) == '\n')

但是我总是遇到段错误^^'。

【问题讨论】:

  • getline 丢弃换行符 - 你永远不会检测到一个
  • 如果getline 返回一个有效的流(在条件下使用它会产生true),那么您实际上检测到了一个换行符。否则函数将不会返回,或者流将是false
  • 如果要检查空行,检查字符串是否为空。
  • @Some 如果你得到一个空字符串,你也检测到一个换行符。
  • @NeilButterworth 是的,已编辑。

标签: c++ input ifstream


【解决方案1】:

使用

if (input_line.at(0) == '\n')

检查空行是否错误,因为std::getline 读取并丢弃分隔符(在您的情况下为'\n')。

改为使用

if (input_line.empty())

【讨论】:

    【解决方案2】:

    std::getline 将丢弃换行符。 您可以检查 std::string::empty() 以检测空行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      • 2020-02-16
      • 2018-03-25
      • 2016-04-20
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      相关资源
      最近更新 更多