0

我正在用 C++ 编写一个程序来比较两个大型 XML 文件,并创建一个包含更改的产品(节点)的标识符和更改的文件。为此,我正在使用pugixml

我现在是一名 PHP 开发人员,自从我使用 c++ 以来已经有一段时间了,所以我认为我忽略了一些微不足道的事情,但是经过数小时的在线搜索后,我仍然没有找到解决我的问题的方法,即:

child_value 函数简单地给出元素标签之间的值,返回一个 const char *。我想要做的是将所有值放入一个数组中,并将它们与所有其他产品的值(它们在一个类似的数组中)进行比较。

转到下一个产品时会出现问题,我需要覆盖数组中的值,我认为这是我得到的分段错误的根源。所以我的问题是:

我需要使用该 const char * 进行比较,但我需要覆盖这些值以便进行下一次比较,最好的方法是什么?我已经尝试过 strcpy、const_cast(如下面的示例代码)和许多其他建议,但似乎都导致了相同的分段错误。

它可以编译,但是当它试图覆盖第一个值时,它只会在第二次迭代时崩溃。

for (xml_node groupCurrent = groupsCurrent.child("group");groupCurrent;groupCurrent = groupCurrent.next_sibling("group")){

    xml_node productsCurrent = groupCurrent.child("products");
    size_t nrProductsInGroupCurrent = std::distance(productsCurrent.children().begin(), productsCurrent.children().end());
    nrProductsTotalCurrent = nrProductsTotalCurrent + nrProductsInGroupCurrent;

    for (xml_node productCurrent = productsCurrent.child("product");productCurrent;productCurrent = productCurrent.next_sibling("product")){

        int numberAttributesC=0;
        char * childrenCurrent[32];

        for (xml_node attributeCurrent = productCurrent.first_child();attributeCurrent ;attributeCurrent= attributeCurrent.next_sibling()){
            char * nonConstValue = const_cast<char *> (attributeCurrent.child_value());
            childrenCurrent[numberAttributesC]=nonConstValue;
            numberAttributesC++;
        }

        /*for(int i = 0;i<numberAttributesC;i++){
            std::cout<<childrenCurrent[i];
        }*/
        //xml_node groupsNew = docNew.child("product_database");

    }
}

非常感谢任何帮助、建议或意见。如果我同时自己找到解决方案,我会在这里发布。

问候,反

PS:在 ubuntu 上使用 gcc 版本 4.8.2

4

1 回答 1

0

只需使用一个vector and string

std::vector<std::string> childrenCurrent;

for (xml_node attributeCurrent = productCurrent.first_child();attributeCurrent ;attributeCurrent= attributeCurrent.next_sibling())
{    
  std::string value = attributeCurrent.child_value();
  childrenCurrent.push_back(value);    
}

注意:我假设这child_value是返回一个const char*

string复制子值,这消除了任何内存问题,并且使用vector将让您不必担心管理潜在属性的数量。

于 2014-11-20T10:14:29.550 回答