【问题标题】:Conversion of ATL CString to character arrayATL CString 到字符数组的转换
【发布时间】:2012-05-21 15:41:10
【问题描述】:

我想将CString 转换为char[]。有人告诉我该怎么做?

我的代码是这样的:

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

【问题讨论】:

  • 感谢大家,我在 WideCharToMultiByte 方法的帮助下通过以下方式解决了这个问题:TCHAR tchCamIPTemp[15]; _tcscpy(tchCamIPTemp, strCamIP1); WideCharToMultiByte(CP_ACP, 0, tchCamIPTemp, -1, g_acCameraip[0], sizeof(g_acCameraip[0]), NULL, NULL);

标签: c++ visual-c++ char c-strings


【解决方案1】:

有一个硬编码的方法..

CString a = L"This is CString!";
char *dest = (char *)malloc(a.GetLength() + 1);
// +1 because of NULL char

dest[a.GetLength()] = 0; // setting null char

char *q = (char *)a.m_pszData;
//Here we cannot access the private member..
//The address of "m_pszData" private member is stored in first DWORD of &a...
//Therefore..

int address = *((int *)&a);

char *q = (char *)address;
// Now we can access the private data!, This is the real magic of C
// Size of CString's characters is 16bit...
// in cstring '1' will be stored as 0x31 0x00 (Hex)
// Here we just want even indexed chars..

for(int i = 0;i<(a.GetLength()*2);i += 2)
  dest[i/2] = *(q+i);

// Now we can use it..
printf("%s", dest);

【讨论】:

    【解决方案2】:

    很简单

    ATL CStrings 允许非常简单的使用,而无需在类型之间进行大量转换。您可以最轻松地做到:

    CString cs = "Test";
    const char* str = static_cast<LPCTSTR>(cs);
    

    或在 UNICODE 环境中:

    CString cs = "Test";
    const wchar_t* str = static_cast<LPCTSTR>(cs);
    

    工作原理

    static_cast(或 C 样式转换)将触发 CString::operator LPCTSTR,因此您无需自己进行任何指针重新解释,而是依赖 ATL 代码!

    这个演员表操作员的文档说:

    这个有用的强制转换运算符提供了一种有效的方法来访问包含在 CString 对象中的以 null 结尾的 C 字符串没有字符被复制;只返回一个指针。小心这个操作符。如果在获取字符指针后更改 CString 对象,可能会导致内存重新分配,从而使指针无效。

    可修改指针

    正如上面所说,强制转换操作符返回的指针不打算修改。但是,如果您仍然需要为某些过时的 C 库使用可修改指针,您可以使用 const_cast(如果您确定该函数不会修改指针):

    void Func(char* str) // or wchar_t* in Unicode environment
    {
        // your code here
    }
    
    // In your calling code:
    CString cs = "Test";
    Func(const_cast<LPTSTR>(static_cast<LPCTSTR>(test))); // Call your function with a modifiable pointer
    

    如果你想修改指针,你不会像其他答案提到的那样将某种内存复制到可修改的内存。

    【讨论】:

      【解决方案3】:
      char strPass[256];
      strcpy_s( strPass, CStringA(strCommand).GetString() );
      

      【讨论】:

        【解决方案4】:
            CString str;
            //Do something
            char* pGTA = (LPTSTR)(LPCTSTR)str;//Now the cast
        

        只是(LPTSTR)(LPCTSTR)。希望这是你需要的:)

        【讨论】:

          【解决方案5】:

          fopen 是需要 char* 参数的函数。所以如果你有 CString 作为可用的字符串,你可以使用下面的代码。 要开心 :) 在这里,cFDlg.GetPathName().GetString(); 基本上在我的代码中返回 CString。

          char*pp  = (char*)cFDlg.GetPathName().GetString();
          FILE *fp = ::fopen(pp,"w");
          

          【讨论】:

            【解决方案6】:

            如果您使用的是 ATL,则可以使用其中一种转换宏。 CString 将数据存储为 tchar,因此您可以使用 CT2A()(宏名称中的 C 代表 const):

            CString from("text");
            
            char* pStr = CT2A((LPCTSTR)from);
            

            那些宏很聪明,如果 tchar 表示 ascii(未定义 _UNICODE),它们只是将指针传递过去,什么也不做。

            更多信息如下,ATL 字符串转换类部分: http://www.369o.com/data/books/atl/index.html?page=0321159624%2Fch05.html

            【讨论】:

            • 我喜欢这个:CString from("text"); CT2A pStr(from);
            【解决方案7】:

            真的必须复制 CString 对象到固定的char 数组吗?

            enum { COUNT=16 };
            CString Cameraip[COUNT];
            Cameraip[0] = theApp.GetProfileString(strSection, _T("IP1"), NULL);
            // add more entries...
            

            ...然后 - 稍后 - 在访问条目时,例如这样

            for (int i=0; i<COUNT; ++i) {
                someOp(Cameraip[i]); // the someOp function takes const CString&
            }
            

            ...您可以convert them如果需要。

            【讨论】:

              【解决方案8】:

              使用 memcpy 。

              char c [25];
              Cstring cstr = "123";
              memcpy(c,cstr,cstr.GetLength());
              

              【讨论】:

                【解决方案9】:

                CStringA/W 可以廉价且隐式地转换为const char/wchar_t *。每当您需要 C 风格的字符串时,只需传递 CString 对象本身(或 .GetString() 的结果相同)。只要字符串对象处于活动状态且未修改,指针就会保持有效。

                strcpy(g_acCameraip[0], strCamIP1);
                // OR
                strcpy(g_acCameraip[0], strCamIP1.GetString());
                

                如果您需要可写(非常量)缓冲区,请使用带有可选最大长度参数的 .GetBuffer()

                如果你有CStringW,但你需要const char*,反之亦然,你可以使用一个临时的CStringA对象:

                strcpy(g_acCameraip[0], CStringA(strCamIP1).GetString());
                

                但更好的方法是拥有CStrings 的数组。您可以在任何需要空终止字符串的地方使用它们,但它们也会为您管理字符串的内存。

                std::vector<CString> g_acCameraip(16);
                g_acCameraip[0] = theApp.GetProfileString(strSection, _T("IP1"), NULL);
                

                【讨论】:

                  【解决方案10】:

                  来自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;
                  

                  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;
                  

                  【讨论】:

                  • origw.GetLength() * 2 +1 也可以吗?
                  【解决方案11】:

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

                  CString aCString = "A string";
                  char myString[256];
                  strcpy(myString, (LPCTSTR)aString);
                  

                  在你的情况下是这样的

                  strcpy(g_acCameraip[0], (LPCTSTR)strCamIP1);
                  

                  【讨论】:

                  • error C2664: 'strcpy' : cannot convert parameter 2 from 'const unsigned short *' to 'const char * 出现错误
                  • 错误类型:\CString aCString = "一个字符串";字符 myString[256]; strcpy(myString, (LPCTSTR)aString);
                  • Imo 这是最好和最简单的方法。如果您想使用 C++ 强制转换,您可以使用static_cast&lt;LPCTSTR&gt;(cstringVar),它将在 unicode 和 MBCS 下工作。
                  • 这在第一行失败:不存在合适的构造函数来从“const char [9]”转换为“ATL::CStringT> >
                  【解决方案12】:

                  你可以使用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
                  

                  【讨论】:

                    猜你喜欢
                    • 2012-06-29
                    • 2010-10-21
                    • 2011-09-07
                    • 2011-01-29
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2012-09-03
                    相关资源
                    最近更新 更多