統計ANSI格式下文件中中文個數(不包括中文運算符)

#include<iostream>
#include<fstream>
using namespace std;
// 關於ANSI,unicode與utf-8的區別:https://blog.csdn.net/forest_fire/article/details/81011090
//以下程序對gb2312編碼有效,文檔格式爲ansi
void  calculate(const char* srcFile)
{
	unsigned char ch[2];
	ifstream inFile(srcFile, ios::in);
	if (!inFile)
	{
		cerr << "File could not be open." << endl;
		exit(-1);
	}
	int all_num = 0;
	string s = "";
	while (true)
	{
		inFile >> ch[0];
		if (inFile.eof())break;
		//GB2312編碼範圍:A1A1-FEFE,
		//其中漢字的編碼範圍爲B0A1-F7FE,第一字節0xB0-0xF7(對應區號:16-87),第二個字節0xA0-0xFE(對應位號:01-94)。
		if (ch[0] >= 0xb0 && ch[0] <= 0xf7)//GB2312下的漢字,最小是0XB0 
		{
			inFile >> ch[1];
			if (ch[1] >= 0xa0 && ch[1] <= 0xfe)
				all_num += 1;
		}
		else
			continue;
	}
	cout << "總中文數" << all_num << endl;
	inFile.close();
}
int main()
{
  calculate("C:\\Users\\Lenovo\\Desktop\\1.txt");
}









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章