zoukankan      html  css  js  c++  java
  • MFC中CString转换成char数组的问题

    由于结构体中用到联合体(联合体需要确定分配内存分配大小)或其它因素,需要用char数组来保存字符串,但是在MFC中一般都是用CString来存放字条串。关于它们之间的转换,在VS2008中有时会出现异常情况。在MSDN是这样写的:

        CString orig("Hello, World!");

        // Convert to a char*
        const size_t newsize = 100;
        char nstring[newsize];
        strcpy_s(nstring, orig);


            但在实际应用中,并不能通过,总会在strcpy_s()函数中出错,或者在nstring的后面跟着很多乱码尾巴。在网上查阅了一些方法。如下:

    方法一:
    char *p;
    CString str="hello";
    p=str.GetBuffer(str.GetLength());
    str.ReleaseBuffer();
    方法二:
    CString str="hello";
    char ch[20];
    memcpy(ch,str,str.GetLength());
    方法三:
    char *ch;
    CString str="hello";
    ch=(LPSTR)(LPCTSTR)str;

    但总达不到期望的结果。随后再在网上查,发现是Unicode字符集的问题。选择项目->项目属性(或直接按alt+F7)->配置属性,在右边找到“字符集”,将“使用Unicode字符集”改为“使用多字节字符集”。保存之后需要重新生成解决方案。这样上面的方法都可以通过并实现,但是在方法二中,最好不要使用memcpy,直接用strcpy_s(char*, CString)就可以了,因为用memcpy也会出现乱码尾巴。

    如果不想改变Unicode字符集,网上也有介绍方法,但我没有试过,在此列出来供网友们参考:

    CString strPath = L"adfafs主声音文件fsfsa";
    int nLength = strPath.GetLength();
    int nBytes = WideCharToMultiByte(CP_ACP,0,strPath,nLength,NULL,0,NULL,NULL);
    char* VoicePath = new char[ nBytes + 1];
    memset(VoicePath,0,nLength + 1);
    WideCharToMultiByte(CP_OEMCP, 0, strPath, nLength, VoicePath, nBytes, NULL, NULL);
    VoicePath[nBytes] = 0;

  • 相关阅读:
    VisualSVN-Server windows 版安装时报错 "Service 'VisualSVN Server' failed to start. Please check VisualSVN Server log in Event Viewer for more details."
    Pytest 单元测试框架之初始化和清除环境
    Pytest 单元测试框架入门
    Python(email 邮件收发)
    Python(minidom 模块)
    Python(csv 模块)
    禅道简介
    2020年最好的WooCommerce主题
    Shopify网上开店教程(2020版)
    WooCommerce VS Magento 2020:哪个跨境电商自建站软件更好?
  • 原文地址:https://www.cnblogs.com/pengkunfan/p/3827033.html
Copyright © 2011-2022 走看看