c++ - 使用 Tinyxml 的段错误

标签 c++ tinyxml

我正在尝试使用 Tinyxml 递归读取 Xml 文件,但是当我尝试访问数据时出现“段错误”。这是代码:

int id=0, categoria=0;
const char* nombre;
do{  
    ingrediente = ingrediente->NextSiblingElement("Ingrediente");   
    contador++;  
    if(ingrediente->Attribute("id")!=NULL)
        id = atoi( ingrediente->Attribute("id") );  
    if(ingrediente->Attribute("categoria")!=NULL)
        categoria = atoi ( ingrediente->Attribute("categoria") );  
    if(ingrediente!=NULL)
        nombre = ( ( ingrediente->FirstChild() )->ToText() )->Value();  
}while(ingrediente);    

出于某种原因,三个“if”行向我抛出了段错误,但我不知道问题出在哪里。

提前致谢。

最佳答案

您将在每次迭代开始时更新 ingrediente,然后在检查它不为空之前取消引用它。如果它为空,这将给出一个段错误。循环可能应该按照

for (ingrediente = first_ingrediente; 
     ingrediente; 
     ingrediente = ingrediente->NextSiblingElement("Ingrediente"))
    contador++;  
    if(ingrediente->Attribute("id"))
        id = atoi( ingrediente->Attribute("id") );  
    if(ingrediente->Attribute("categoria"))
        categoria = atoi ( ingrediente->Attribute("categoria") );  
    nombre = ingrediente->FirstChild()->ToText()->Value();  
}

很抱歉在变量名中混入了一些英文;我不会说西类牙语。

或者,如果 NextSiblingElement 在您开始迭代时为您提供了第一个元素,则可以将 for 替换为 while:

while ((ingrediente = ingrediente->NextSiblingElement("Ingrediente")))

重要的一点是在获取指针之后和取消引用之前检查是否为 null。

关于c++ - 使用 Tinyxml 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3481385/

相关文章:

c++ - 如何初始化作为类成员的 shared_ptr?

c++ - 如何在 C++ 中初始化具有相同值的二维数组

c++ - TinyXML - 有什么方法可以跳过有问题的 DOCTYPE 标签吗?

c++ - 我应该使用 XPath 还是只使用 DOM?

c++ - 使用堆栈添加带有组件的 2 个 vector 组件

c++ - 打开CV "vector iterators incompatible"

c++ - 使用 vowpal wabbit 的典型技术堆栈?

c++ - TinyXML 的 UTF-8 支持如何工作?

c++ - Tinyxml2 根集属性

c++ - tinyxml 解析xml文件