當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ mbrlen()用法及代碼示例

C++ 中的mbrlen() 函數確定多字節字符的字節大小。

mbrlen() 函數在<cwchar> 頭文件中定義。

mbrlen()原型

size_t mbrlen( const char* s, size_t n, mbstate_t* ps);

mbrlen() 函數檢查第一個字節由 s 指向的字符串,並確定當前轉換狀態 ps 的字節大小。最多檢查s 中的n 字節。

參數:

  • s:指向要檢查的多字節字符串的第一個字節的指針。
  • n:要檢查的 s 中的最大字節數。
  • ps:指向定義轉換狀態的 mbstate_t 對象的指針。

返回:

mbrlen() 函數返回:

  • 完成有效多字節字符的字節數。
  • 如果 s 指向空字符,則為 0。
  • -1 是發生編碼錯誤。
  • -2 如果接下來的 n 個字節不代表一個完整的多字節字符。

示例:mbrlen() 函數如何工作?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

void test_mbrlen(const char *s, size_t n)
{
	mbstate_t ps = mbstate_t();
	int retVal = mbrlen(s, n, &ps);

	if (retVal == -2)
		cout << "Next " << n << " byte(s) doesn't represent a complete multibyte character" << endl;
	else if (retVal == -1)
		cout << "Next " << n << " byte(s) doesn't represent a valid multibyte character" << endl;
	else
		cout << "Next " << n << " byte(s) of " << s << " holds " << retVal << " byof multibyte character" << endl;
}

int main()
{
	setlocale(LC_ALL, "en_US.utf8");
	char str[] = "\u00b5";

	test_mbrlen(str, 1);
	test_mbrlen(str, 5);

	return 0;
}

運行程序時,輸出將是:

Next 1 byte(s) doesn't represent a complete multibyte character
Next 5 byte(s) of µ holds 2 bytes of multibyte character

相關用法


注:本文由純淨天空篩選整理自 C++ mbrlen()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。