I'm pretty much starting out with C++ and in making a simple console program ran into a problem I couldn't solve. I looked everywhere for the solution and didn't find it so I'll try asking.
I want to save data from a string to xml file with SetText()
, but it only takes char
arrays.
I have a struct
for "person" that looks like this:
struct person {
int Id = 0;
string Name;
char cname[20];
string LastName;
char clastname[20];
int Age;
};
After entering people, I can save to XML. With a for
loop I save each person.
This code is from a for
loop..
//save name
string pName = p.Name;
XMLElement* pername = doc.NewElement("pname");
pername->SetText(p.cname);
pers->InsertEndChild(pername);
It works fine. But while loading it only populates the string Name
and not the char cname
. So when saving again the loaded people name is not saved correctly.
This is how I load the name...
XMLElement* p_name = p_person->FirstChildElement("pname");
string pname = p_name->GetText();
nPerson.Name = pname;
So I'm thinking of 2 different solutions.
- Saving directly from string Name, and removing cname completely from the person struct.
- When loading, somehow convert string to char array so i can resave without errors.
I hope the question is understandable. I apologise but english is not my first language :)
I tried converting string to char
array before saving...
const int namelength = pName.length();
char* char_array_name = new char[namelength + 1];
char_array_name[namelength] = '\0';
for (int i = 0; i < namelength; i++)
{
char_array_name[i] = pName[i];}
pername->SetText(char_array_name);
...but it saves only the first letter of the name.
I tried converting after loading but couldn't do it either. I've spent a lot of time before posting the question but as I said. I am a beginner so maybe the answer is obvious and I just can't see it.
SOLVED
Just use pName.c_str()
. This will return a const char *
.
As a beginner I was overcomplicating things. One to the point answer helped me get it. Thanks again user20716902 :)