将ATL CString转换为字符数组

Vai*_*hav 4 c++ c-strings char visual-c++

我想把a转换CString成a char[].有人告诉我怎么做?

我的代码是这样的:

CString strCamIP1 = _T("");
char g_acCameraip[16][17];
strCamIP1 = theApp.GetProfileString(strSection, _T("IP1"), NULL);
g_acCameraip[0] = strCamIP1;
Run Code Online (Sandbox Code Playgroud)

dut*_*utt 7

这似乎沿着正确的路线; http://msdn.microsoft.com/en-us/library/awkwbzyc.aspx

CString aCString = "A string";
char myString[256];
strcpy(myString, (LPCTSTR)aString);
Run Code Online (Sandbox Code Playgroud)

在你的情况下,这将是沿着的

strcpy(g_acCameraip[0], (LPCTSTR)strCamIP1);
Run Code Online (Sandbox Code Playgroud)

  • 我得到一个错误,因为`错误C2664:'strcpy':无法将参数2从'const unsigned short*'转换为'const char*' (5认同)

psu*_*sur 7

来自MSDN网站:

// Convert to a char* string from CStringA string 
// and display the result.
CStringA origa("Hello, World!");
const size_t newsizea = (origa.GetLength() + 1);
char *nstringa = new char[newsizea];
strcpy_s(nstringa, newsizea, origa);
cout << nstringa << " (char *)" << endl;
Run Code Online (Sandbox Code Playgroud)

CString基于TCHAR这样,如果不用_UNICODE它编译,CStringA或者如果你用它编译_UNICODE那么它就是CStringW.

如果CStringW转换看起来有点不同(例如也来自MSDN):

// Convert to a char* string from a wide character 
// CStringW string. To be safe, we allocate two bytes for each
// character in the original string, including the terminating
// null.
const size_t newsizew = (origw.GetLength() + 1)*2;
char *nstringw = new char[newsizew];
size_t convertedCharsw = 0;
wcstombs_s(&convertedCharsw, nstringw, newsizew, origw, _TRUNCATE );
cout << nstringw << " (char *)" << endl;
Run Code Online (Sandbox Code Playgroud)


gli*_*ite 3

您可以使用wcstombs_s

// Convert CString to Char By Quintin Immelman.
//
CString DummyString;
// Size Can be anything, just adjust the 100 to suit. 
const size_t StringSize = 100;
// The number of characters in the string can be
// less than String Size. Null terminating character added at end.
size_t CharactersConverted = 0;

char DummyToChar[StringSize];

wcstombs_s(&CharactersConverted, DummyToChar, 
       DummyString.GetLength()+1, DummyString, 
       _TRUNCATE);
//Always Enter the length as 1 greater else 
//the last character is Truncated
Run Code Online (Sandbox Code Playgroud)