Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concat CStrings??

Status
Not open for further replies.

michaelkrauklis

Programmer
Dec 5, 2001
226
US
I'm having a little problem with strings, particularly conversion and manipulation of CString/char*. Now am I correct in assuming that CStrings are NULL terminated? And when you create a char* in the manner of "the string" that is alwo NULL terminated, right? My problem is weird, because it doesn't seem to fail in any special case. Here's my simplified code.
Code:
char *base=(char*)calloc(1,8);
base[0]=NULL;
for(all CStrings){
  base=(char*)realloc(base,strlen(base)+CString->getLength()+1);
  strcat(base,CString->GetBuffer(0));
  strcat(base,",");
}
the actual code is a bit more complicated but that's the basic idea. The code works the first time through perfectly, but the second time through and the subsequent times after that I get garbage until I eventually get a memory(out of bounds) exception. Is there something wrong with this code? And am I correct in my assumptions that these strings should be NULL terminated?

Also, if this isn't good is there an easy way to concatonate CStrings?

Thanks! MYenigmaSELF:-9
myenigmaself@yahoo.com
 
Ok, the MSDN reference doesn't show the overloaded operators for CString. I finaly found them in the VC++ reference, so I guess that's the route I'm going to go. (+ and += are overloaded for CString) Thanks anyway. MYenigmaSELF:-9
myenigmaself@yahoo.com
 
Hi

CString are not NULL terminated strings. It's a variable-length sequence of characters with its length stored at the beginning (if I remember well ....)

To concatenate simply do this:

CString str1;
CString str2;
CString str3;

str1 = "this is a ";
str2 = "test";
str3 = str1 + str2;

HTH

Thierry
EMail: Thierry.Marneffe@swing.be

 
Yep, thanks. I've figured that out. The documentation I was looking at didn't have the overloaded operators but I've found them in the VC++ documentation. And the strings that I encapsulated in the CStrings were NULL terminated I believe, but that's irrelavant now that I'm doing it using +=. Thanks for the help MYenigmaSELF:-9
myenigmaself@yahoo.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top