Home > General > How to translate among CString,string and char array

How to translate among CString,string and char array

June 22nd, 2007

In MFC program, you’d better try to avoid using std::string. There is no compelling reason to use it in MFC, and it leads to confusion.

There are some standard method to translate among Cstring ,string and char[].

// Suppose
CString str;
std::string s;
char buf[SIZE];
 
// from CString to std::string
s = str;
 
// from std::string to CString
str = s.c_str();
 
// to char[]
_tcscpy(buf, str);
_tcscpy(buf, s.c_str());
 
// from char[]
str = buf;
s = buf;

Also, beware of unicode. If UNICODE is defined, you should convert between unicode and ansi versions. Better to use TCHAR instead of char and std::basic_string instead of std::string.

General , , ,

  1. No comments yet.
  1. No trackbacks yet.