View Single Post
Old 03-12-2005, 10:23 AM   #12 (permalink)
DJMaze
Senior Contributor
 
DJMaze's Avatar
 
Join Date: Mar 2005
Posts: 673
DJMaze is on a distinguished road
i was searching for the function to merge _UNICODE strings since i forgot the name

Although this topic is very old it is also maybe nice to tell how to use these functions and such in a unicode vs. ansi environment since these days more and more people are coding in UTF.

strcopy() is ANSI only and wcscpy() is UNICODE but what if your app should support both, or you're creating files that are used by several projects ANSI and UNICODE ?

International API routines solve your issues

_tcscpy() = strcpy() / wcscpy()
_tcscat() = strcat() / wcscat()
_tcslen() = strlen() / wcslen()

TCHAR = char / wchar_t

Code:
int main(){
  TCHAR* hello = _T("Hello ");
  TCHAR* world = _T("world");
  TCHAR hello_world[50];
  int index_hello=0, index_world=0;
  while(hello[index_hello])
    hello_world[index_hello]=hello[index_hello++];
  while(world[index_world])
    hello_world[index_hello++]=world[index_world++];
  hello_world[index_hello]='\0';
  _tprintf("%s\n", hello_world);
  return 1;
}
Code:
int main()
{
	TCHAR* szHello = _T("Hello");
	TCHAR szHowdy[] = _T("Everybody");
	
	//strlen() returns the size in bytes, so we need to add +1 later. Guess why.	
	int len = _tcslen(szHello)+_tcslen(szHowdy);
	//So szGreetAll has the size of szHello and szHowdy PLUS 2 for the terminating character and...
	//...for the extra space we insert between szHello and szHowdy!
	char* szGreetAll=new TCHAR[len+2];
	//Line below: the way to copy and merge strings.
	_tcscpy(szGreetAll, szHello); //copy szHello to our buffer.
	_tcscat(szGreetAll, _T(" ")); //Merge it with an extra space.
	_tcscat(szGreetAll, szHowdy); //And then glue szHello to the end of the buffer.
	cout<<szGreetAll<<endl;
	
	return 0;
}
As you see _T() is used to properly identify the string as char or wchar_t depending if you compile the code using _UNICODE or just plain ANSI.

NOTE: you need to use
Code:
#include <tchar.h>
which is a M$ SDK file, but shure you can create your own.


Just my $0.02
DJMaze is offline   Reply With Quote