我目前在UNIX和COBOL上工作,並且已經達到了我需要在接收到的消息中提供中文和韓文字符數的計劃,我計劃在C程序使用mbstows。mbsctows來計算一個數組中的寬字符數
我正在使用下面的代碼,它沒有給出中文雙字節字符的正確計數,但給出了字節數。
#include <wchar.h>
#include <stdio.h>
#include <locale.h>
int main(int argc, char *argv[])
{
if (argc != 2) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf("usage: %s filename", argv[0]);
}
int Size = getCharCount(argv[1]);
printf ("THE CHAR COUNT %d", Size);
return Size;
}
int getCharCount(char *argv)
{
wchar_t *wcsVal = NULL;
char *mbsVal = NULL;
char* localeInfo;
setlocale(LC_ALL, "zh_CN.GB18030");
/* verify locale is set */
if (setlocale(LC_ALL, "") == 0)
{
/* printf(stderr, "Failed to set locale\n"); */
return 1;
}
mbsVal = argv;
printf (" MBSVAL %s\n", mbsVal);
/* validate multibyte string and convert to wide character */
int size = mbstowcs(NULL, mbsVal, 0);
if (size == -1)
{
printf("Invalid multibyte\n");
return 1;
}
return size;
}
感謝您的一種迴應...
問候
AKM
嗨,非常感謝您的回覆。我試着評論所提到的代碼,但代碼仍然不起作用。我試圖給這個程序的輸入是:½ÒøÐк£ÐÂÂÐÐÐWhich這是一個雙字節漢字字節流。它實際上有20個字節,但是我的C程序應該確定它們是中文字符,並且由於它們是雙字節字符,所以我的計數爲10。任何迴應將非常感謝...提前致謝... – Abhijeet 2011-01-25 02:13:50
您確定您設置的語言環境安裝在您的系統上?如果在shell中執行LC_ALL或LC_CTYPE的設置,它是否被OS接受? – 2011-01-25 09:00:31