【问题标题】:Problem: How to convert CString into const char * in C++ MFC问题:如何在 C++ MFC 中将 CString 转换为 const char *
【发布时间】:2011-07-26 11:13:15
【问题描述】:

如何将 CString 转换为 const char *?我已经尝试了在互联网上找到的所有内容,但我仍然无法转换它们。

请帮忙。

谢谢。

【问题讨论】:

标签: c++ visual-c++ mfc


【解决方案1】:

首先:定义 char *inputString;在 your_file.h 中

第二:在 yourFile.cpp 中定义: CString 我的字符串;

MyString = "Place here whatever you want";

inputString = new char[MyString.GetLength()];
inputString = MyString.GetBuffer(MyString.GetLength());

最后两句将 CString 变量转换为 char*;但要小心,使用 CString 您可以保存数百万个字符,但使用 char* 没有。您必须定义 char* 变量的大小。

【讨论】:

    【解决方案2】:

    CString 直接转换为 const char *

    CString temp;
    temp = "Wow";
    const char * foo = (LPCSTR) temp;
    printf("%s", foo);
    

    将打印'foo'

    较新版本的 MFC 也支持 GetString() 方法:

    CString temp;
    temp = "Wow";
    const char * foo = temp.GetString();
    printf("%s", foo);
    

    【讨论】:

    • 错误 C2440: 'type cast': 无法从 'ATL::CString' 转换为 'LPCSTR'
    【解决方案3】:

    我知道已经晚了,但我无法使用标记为答案的解决方案。我在整个互联网上搜索,没有任何东西对我有用。我努力解决问题:

    char * convertToCharArr(CString str) {
        int x = 0;
        string s = "";
        while (x < str.GetLength()) {
            char c = str.GetAt(x++);
            s += c;
        }
        char * output = (char *)calloc(str.GetLength() + 1, sizeof(char));
        memcpy(output, s.c_str(), str.GetLength() + 1);
        return output;
    }
    

    【讨论】:

      【解决方案4】:

      简答:使用CT2CA 宏(请参阅ATL and MFC String Conversion Macros)。无论您的项目的“字符集”设置如何,这都将起作用。

      长答案:

      • 如果您定义了UNICODE 预处理器符号(即,如果TCHARwchar_t),请使用CT2CACW2CA 宏。
      • 如果不这样做(即,如果 TCHARchar),CString 已经有一个运算符可以隐式转换为 char const*(请参阅 CSimpleStringT::operator PCXSTR)。

      【讨论】:

        【解决方案5】:

        如果您的应用程序不是 Unicode,您可以简单地类型转换为 const char *。如果您需要可以修改的char *,请使用GetBuffer() 方法。

        如果您的应用程序是 Unicode 并且您确实想要 char *,那么您需要对其进行转换。 (可以使用MultiByteToWideChar()等函数。)

        【讨论】:

          猜你喜欢
          • 2012-09-17
          • 2010-10-25
          • 2015-07-03
          • 2012-03-22
          • 2012-11-07
          • 2020-06-12
          • 2014-10-22
          • 2019-11-11
          相关资源
          最近更新 更多