MFC CString 轉換成CHAR陣列

2021-08-19 15:10:56 字數 1337 閱讀 4194

由於結構體中用到聯合體(聯合體需要確定分配記憶體分配大小)或其它因素,需要用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;

MFC CString型別轉換

1 cstring 物件的連線 能體現出 cstring 型別方便性特點的乙個方面就字串的連線,使用 cstring 型別,你能很方便地連線兩個字串,正如下面的例子 cstring gray gray cstring cat cat cstring graycat gray cat 要比用下面的方法...

漢字轉換成拼音

c 乙個有用的漢字轉拼音類 c 漢字轉換為拼音的類,含大小寫轉換 因為是靜態函式 呼叫方法很簡單 crazycoderpinyin.convert 瘋狂 如下 using system using system.collections.generic using system.text using ...

分數轉換成小數

問題描述,輸入兩個整數a,b,將分數輸出a b的小數格式,如果a b是迴圈小數,則將迴圈部分用括號括起來,例如 1 4 0.25 1 3 0.3 1 6 0.1 6 分析 實質上是實現高精度浮點數除法。借助雜湊表來獲取迴圈部分。public class solution static int b i...