Assigning char * to CString Object :: C++

kuphryn

Senior member
Jan 7, 2001
400
0
0
Hi.

I have a char * to a data buffer. What is the best way to assign data from char * into a CString object? For example:

-----
// char *myChar = new char[10];
// memcpy(myChar, "abcdefghij", 10);
// CString myString;
-----

What is the best say to insert data from myChar into myString?

Thanks,
Kuphryn
 

Adrian Tung

Golden Member
Oct 10, 1999
1,370
1
0
Just a note in your code: you should use strcpy or strncpy instead of memcpy for your code. Also remember that your strings are null-terminated, so you should always have one element more than the number of character in your string for the null character.

char *myChar = new char[11];
strcpy(myChar, "abcdefghij"); // -> your string is actually { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', '\0' }
CString myString = myChar;


:)atwl
 

kuphryn

Senior member
Jan 7, 2001
400
0
0
Thanks.

I added a null terminator.

Why do you prefer strcpy over memcpy? From what I know, memcpy can handle both null-terminated string and raw data buffer.

Kuphryn
 

Adrian Tung

Golden Member
Oct 10, 1999
1,370
1
0
True, memcpy can handle them but you don't always know the length of your strings. In such situations, strcpy will be more efficient compared to a strlen+memcpy.


:)atwl
 

CodeJockey

Member
May 1, 2001
177
0
0
Based on your example code, you could also use the CString constructor:

Instead of

CString myString;

use

CString myString( myChar, 10 );

which will construct the CString and initialize it with the 10 characters from the myChar array.
 

kuphryn

Senior member
Jan 7, 2001
400
0
0
Nice! Thanks.

For the second parameter, do I include the null-terminator too?

-----
// char *myChar = new char[11];
// strcpy(myChar, "abcdifghi");
// myChar[10] = '\0';
// CString myString(myChar, ???)
-----

??? = 10 or 11

Kuphryn
 

CodeJockey

Member
May 1, 2001
177
0
0
That's up to you.

The CString itself will add a null terminator to it's internal copy of the string, after the specified number of characters have been copied.

Examples:

CString str3( "abc", 3 ); // str3 = {'a', 'b', 'c', '\0'}
CString str4( "abc", 4 ); // str4 = {'a', 'b', 'c', '\0', '\0'}

str3.GetLength() will return 3
str4.GetLength() will return 4

of course, easier still is to use

CString str( "abc" );

If you are trying to work with blocks of binary data that might contain values from 0x80 through 0xff, inclusive, or might contain embedded nulls (0x00), then you are probably better off using arrays of unsigned char, since the CString class is not designed to handle anything but null terminated character strings.