getline在读取文本文件时有奇怪的行为

问题描述 投票:0回答:1

我对自己编写的一段代码有奇怪的行为。有代码:

#include "pugixml.hpp"

#include <cassert>
#include <string>
#include <iostream>
#include <fstream>
#include <optional>

namespace xml = pugi;

void read_ascii_file(const std::string& filename)
{
  std::ifstream file(filename, std::ios::in);

  if(!file) {
    std::cerr << "[ERREUR - read_ascii_file] Impossible d'ouvrir le fichier " << filename << "! Vérifier son existence." << std::endl;
    abort();
  }

  std::string tmp;
  while(std::getline(file, tmp))
    {
      //Do nothing here
    }
  file.close();
}

class Foo{

public:
  Foo(const xml::xml_document& doc)
  {
    _base_node = doc.child("test");

    std::string id = _base_node.child("data1").child_value("id");
    std::cout << "id from constructor " << id <<std::endl;
  }

  void bar()
  {
    std::string id = _base_node.child("data2").child_value("id");
    std::cout << "id from bar " << id <<std::endl;
  }

private:
  xml::xml_node _base_node;

};

std::optional<Foo> make(const std::string& filename)
{
  xml::xml_document doc;
  xml::xml_parse_result result = doc.load_file(filename.c_str());

  if(result.status != xml::xml_parse_status::status_ok)
    return {};
  else
    return Foo(doc);
}

int main()
{
  std::string filename = "xml_test.dat";
  std::optional<Foo> f = make(filename);

  if(!f)
    std::abort();
  else
    {
      std::string filename = "lbl-maj_for_test.dat";
      //read_ascii_file(filename);
      f->bar();
    }

  return 0;
}

文件xml_test.dat为:

<test>
  <data1>
    <id>1</id>
  </data1>
  <data2>
    <id>2</id>
  </data2>
</test>

此代码提供输出:

来自构造函数1的ID

第2条的ID

但是当我取消注释行//read_ascii_file(filename);时,输出变为:

来自构造函数1的ID

细分细分

gdb给我错误:

#0  0x00007ffff7f84b20 in pugi::xml_node::child(char const*) const () from /lib/x86_64-linux-gnu/libpugixml.so.1
#1  0x00005555555578ba in Foo::bar (this=0x7fffffffdf40) at /home/guillaume/dev/C++/projects/moteur_de_calcul/test/test_xml_node.cpp:42
#2  0x00005555555575ec in main () at /home/guillaume/dev/C++/projects/moteur_de_calcul/test/test_xml_node.cpp:73

文件lbl-maj_for_test.dat是132行的txt文件,长度似乎都不超过50个字符。我认为是编码问题,但我不知道如何解决此问题...

c++ encoding getline
1个回答
0
投票

getline无关。当您的程序具有undefined behaviour时,取消注释/注释可能会导致这样的红色鲱鱼。

问题是您的节点都悬空了,因为您没有坚持[C0​​]。在您呼叫doc时,bar()已死/无效/孤立。

来自_base_node

xml_document是整个文档结构的所有者;破坏文档会破坏整个树。

假设库支持它,我将[[mo0 the documentation放入doc,并按值将其存储为成员。

© www.soinside.com 2019 - 2024. All rights reserved.