1

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.

  1. Saving directly from string Name, and removing cname completely from the person struct.
  2. 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 :)

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • 1
    Just use `pName.c_str()` This will return a `const char *` – user20716902 Apr 04 '23 at 14:51
  • Thanks! It actually solved the problem! I was overcomplicating things with c_str before. – MatthieuCross Apr 04 '23 at 15:24
  • While the issue was fixed by using `c_str()`, it is worth mentioning that you only load the name data into `pName` but you don't copy it over to `cname`, so `cname` will always be an empty array. – UndergroundCoding Apr 04 '23 at 20:07
  • I know that. I was actually only using cname for saving to xml.Consloe input now saves to string variable Name (not cname like before).I removed it from the person struct and use only string Name now which is fine for what I need here. Thanks – MatthieuCross Apr 04 '23 at 20:37

0 Answers0