mbrtowc
多位元組字元轉換為相等的寬字元。
size_t mbrtowc(
wchar_t *wchar,
const char *mbchar,
size_t count,
mbstate_t mbstate
);
參數
wchar
接收轉換後的寬字元字串的寬字元的位址 (型別wchar_t)。 這個值可以是NULL需要寬字元沒有傳回時。mbchar
一連串的位元組 (多位元組字元) 的地址。count
若要檢查的位元組數目。mbstate
轉換狀態。 如果這個值是 NULL,則會使用內部的轉換狀態類別。
傳回值
0
如果下一個count或更少的位元組完成多位元組字元,表示NULL寬字元。> 0
如果下一個count或較少的位元組完成有效的多位元組字元,則傳回值是完成多位元組字元的位元組數目。-1
如果發生編碼錯誤,此種情況下count或更少的位元組不會完整且正確的多位元組字元、 errno 值會是 EILSEQ 和模稜兩可的轉換狀態。-2
如果下一個count提供給不完整的多位元組的位元組,並在處理完所有的數個位元組。
備註
如果wchar是 NULL 值,此函式相當於呼叫:
mbrtowc(NULL, NULL, 1, mbstate)
此時引數的值是wchar和count會被忽略。
如果wchar不是 NULL,此函式會檢查count位元組mbchar來決定所需的完成下一個多位元組字元所需的位元組數目。 如果下一個字元是有效的對應的多位元組字元會儲存在wchar如果不是 NULL。 如果字元是相對應的寬 NULL 字元,則產生的狀態會是初始轉換狀態。
mbrtowc函式會不同於mbtowc _mbtowc_l由其重新。 轉換狀態儲存在mbstate進行後續的呼叫至相同或其他可重新啟動的功能。 混合的重新啟動的和即可函式使用時,結果是未定義。 例如,應用程式會使用wcsrlen而不是wcslen,如果的後續呼叫wcsrtombs而不是使用wcstombs。
範例
將多位元組字元轉換為其對等的萬用字元。
// crt_mbrtowc.cpp
#include <stdio.h>
#include <mbctype.h>
#include <string.h>
#include <locale.h>
#include <wchar.h>
#define BUF_SIZE 100
int Sample(char* szIn, wchar_t* wcOut, int nMax)
{
mbstate_t state = {0}; // Initial state
size_t nConvResult,
nmbLen = 0,
nwcLen = 0;
wchar_t* wcCur = wcOut;
wchar_t* wcEnd = wcCur + nMax;
const char* mbCur = szIn;
const char* mbEnd = mbCur + strlen(mbCur) + 1;
char* szLocal;
// Sets all locale to French_Canada.1252
szLocal = setlocale(LC_ALL, "French_Canada.1252");
if (!szLocal)
{
printf("The fuction setlocale(LC_ALL, \"French_Canada.1252\") failed!\n");
return 1;
}
printf("Locale set to: \"%s\"\n", szLocal);
// Sets the code page associated current locale's code page
// from a previous call to setlocale.
if (_setmbcp(_MB_CP_SBCS) == -1)
{
printf("The fuction _setmbcp(_MB_CP_SBCS) failed!");
return 1;
}
while ((mbCur < mbEnd) && (wcCur < wcEnd))
{
//
nConvResult = mbrtowc(wcCur, mbCur, 1, &state);
switch (nConvResult)
{
case 0:
{ // done
printf("Conversion succeeded!\nMultibyte String: ");
printf(szIn);
printf("\nWC String: ");
wprintf(wcOut);
printf("\n");
mbCur = mbEnd;
break;
}
case -1:
{ // encoding error
printf("The call to mbrtowc has detected an encoding error.\n");
mbCur = mbEnd;
break;
}
case -2:
{ // incomplete character
if (!mbsinit(&state))
{
printf("Currently in middle of mb conversion, state = %x\n", state);
// state will contain data regarding lead byte of mb character
}
++nmbLen;
++mbCur;
break;
}
default:
{
if (nConvResult > 2) // The multibyte should never be larger than 2
{
printf("Error: The size of the converted multibyte is %d.\n", nConvResult);
}
++nmbLen;
++nwcLen;
++wcCur;
++mbCur;
break;
}
}
}
return 0;
}
int main(int argc, char* argv[])
{
char mbBuf[BUF_SIZE] = "AaBbCc\x9A\x8B\xE0\xEF\xF0xXyYzZ";
wchar_t wcBuf[BUF_SIZE] = {L''};
return Sample(mbBuf, wcBuf, BUF_SIZE);
}
範例輸出
Locale set to: "French_Canada.1252"
Conversion succeeded!
Multibyte String: AaBbCcÜïα∩≡xXyYzZ
WC String: AaBbCcÜïα∩≡xXyYzZ
需求
常式 |
所需的標頭 |
---|---|
mbrtowc |
<wchar.h> |
.NET Framework 對等用法
不適用。 若要呼叫標準的 c 函式,使用PInvoke。 如需詳細資訊,請參閱平台叫用範例。