开发者

How to store the values of element values but it is referencing final address

when i am storing data into an array after performing parsing an xml file we have to store it in an array but here it stores like the final address of xml file i.e. it stores all the values but the problem is it all values are referencing to one address so i used vector now for getting all the values, so is there any possibility to get all the values without using any predefined methods.

My code is like,

while(attr){            
                if(!xmlStrcmp(attr->name,(const xmlChar *)"user")){
                    sprintf((char *)UserName.c_str(),"%s",attr->children->content);
                    std::cout<<"UserName: "<<UserName.c_str()<<"\t\t";
                    UN.push_bac开发者_如何学Gok(UserName.c_str());
                }
                if(!xmlStrcmp(attr->name,(const xmlChar *)"password")){
                    sprintf((char *)Password.c_str(),"%s",attr->children->content);
                    std::cout<<"Password: "<<Password.c_str()<<std::endl;
                    PWD.push_back(Password.c_str());
                }
                attr=attr->next;
            }

even vectors also, i am getting same problem so how can i solve this.


I think the problem is that you are storing values somewhere in a vector that aren't supposed to be stored permanently. In particular, this line:

UN.push_back(UserName.c_str());

Seems to be storing the result of UserName.c_str() into a vector<const char*>. If you do this, then you'll run into trouble as soon as you modify the UserName string, or when that string goes out of scope. The value of c_str() is pretty fragile - it's not valid after doing just about anything to the source string - and exists primarily so that you can take string data and pass it into C code that needs a const char* as an argument.

To fix this, I would suggest either explicitly copying the strings before inserting them into the vector:

UN.push_back(strdup(UserName.c_str());

(You don't have to use strdup here; it's just an example)

Alternatively, consider storing std::strings in the vector, which own the string resource they point at and don't have this problem.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜