Is there a better way to modify a char array in a struct? C++

I am trying to read in a cstring from a edit control box in MFC, then put it into a char array in a struct, but since I cannot do something like clientPacket->path = convertfuntion(a); I had to create another char array to store the string then store it element by element.

That felt like a bandait solution, is there a better way to approach this? I'd like to learn how to clean up the code.

CString stri;//Read text from edit control box and convert it to std::string
GetDlgItem(IDC_EDIT1)->GetWindowText(stri);
string a;
a = CT2A(stri);
char holder[256];

strcpy_s(holder,a.c_str());
int size = sizeof(holder);

struct packet {
    char caseRadio;
    char path[256];
};
packet* clientPacket = new packet;
for (int t = 0; t < size; t++) {
    clientPacket->path[t] = holder[t] ;
}

EDIT:This is currently what I went with:

CString stri;//Read text from edit control box and convert it to std::string
GetDlgItem(IDC_EDIT1)->GetWindowText(stri);
string a = CT2A(stri);

struct packet {
    char caseRadio;
    char path[CONSTANT];//#define CONSTANT 256
};
packet* clientPacket = new packet;

a = a.substr(0, sizeof(clientPacket->path) - 1);
strcpy_s(clientPacket->path, a.c_str());

I got a problem where I got "1path" instead of "path", turns out it read in caseRadio='1', fixed it by reading out caseRadio first in the server


You can copy directly into a user-provided buffer when using the Windows API call GetWindowTextA. The following illustrates how to do this:

struct packet {
    char caseRadio;
    char path[512];
} p;

::GetWindowTextA(GetDlgItem(IDC_EDIT1)->GetSafeHwnd(), &p.path[0],
                 static_cast<int>(sizeof(p.path)));

This does an implicit character encoding conversion using the CP_ACP code page. This is not generally desirable, and you may wish to perform the conversion using a known character encoding (such as CP_UTF8).


I don't see the need to create the intermediate 'holder' char array. I think you can just directly do

strcpy(clientPacket->path, a.c_str());

You may want to do this:

a= a.substr(0, sizeof(clientPacket->path)-1);

before the strcpy to avoid buffer overrun depending on whether the edit text is size limited or not.