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


when storing data array after performing parsing xml file have store in array here stores final address of xml file i.e. stores values problem values referencing 1 address used vector getting values, there possibility values without using predefined methods.

my code 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_back(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, getting same problem how can solve this.

i think problem storing values somewhere in vector aren't supposed stored permanently. in particular, line:

un.push_back(username.c_str()); 

seems storing result of username.c_str() vector<const char*>. if this, you'll run trouble modify username string, or when string goes out of scope. value of c_str() pretty fragile - it's not valid after doing source string - , exists can take string data , pass c code needs const char* argument.

to fix this, suggest either explicitly copying strings before inserting them vector:

un.push_back(strdup(username.c_str()); 

(you don't have use strdup here; it's example)

alternatively, consider storing std::strings in vector, own string resource point @ , don't have problem.

hope helps!


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -