1. 程式人生 > >利用位運算統計文字文件中的漢字字數

利用位運算統計文字文件中的漢字字數

在做C++教材練習題時,其中一題要求統計文字文件中的漢字個數,當我直接按char ch做的時候,發現統計出的字數和文字文件的位元組數相同。why?
也就是說,常規方法下統計的實際不是文字文件中的字元個數,而是這些字元的位元組和。
下面是我原先的程式碼:

#include <iostream>
#include <strstream>
#include <fstream>
#include <io.h>
#include <string.h>

using namespace std;

int FrequencyCounts(char
*); int main() { long handle; struct _finddata_t info; handle = _findfirst("*.txt", &info); if (handle == -1) return 0; int count[3]; int i = 0; do { count[i] = FrequencyCounts(info.name); ++i; } while (_findnext(handle, &info) == 0); char
output_name[100]; strcpy(output_name, "多個檔案漢字字頻統計結果.txt"); ofstream out; out.open(output_name, ios::app); if (!out) { cout << "Can't open the file!" << output_name << endl; exit(0); } for (i = 0; i < 3; ++i) { out << "test"
<< i+1 << ".txt" << "中共有" << count[i] << "個字" << endl; } out.close(); cout << "統計完畢" << endl; return 0; } int FrequencyCounts(char *a) { ifstream in(a); if (!in) { cout << "Can't open the file!" << a << endl; exit(0); } char ch; int count = 0; while (in.get(ch)) { count++; } in.close(); return count; }

最後如何改正呢?參考https://blog.csdn.net/bufanq/article/details/51034156的文章,
改為:

    while (in.get(ch))
    {
        if((ch & 0x80) == 0x80)
            count++;
    }

僅此記錄。