博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用位运算统计文本文档中的汉字字数
阅读量:4177 次
发布时间:2019-05-26

本文共 1322 字,大约阅读时间需要 4 分钟。

在做C++教材练习题时,其中一题要求统计文本文档中的汉字个数,当我直接按char ch做的时候,发现统计出的字数和文本文档的字节数相同。why?

也就是说,常规方法下统计的实际不是文本文档中的字符个数,而是这些字符的字节和。
下面是我原先的代码:

#include 
#include
#include
#include
#include
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;}

最后如何改正呢?参考的文章,

改为:

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

仅此记录。

转载地址:http://pptai.baihongyu.com/

你可能感兴趣的文章
单片机跑马灯代码示例
查看>>
Vivo 手机升级最新系统,Android Studio不能再调试,报The application could not be installed: INSTALL_FAILED_TEST_ONLY
查看>>
74HC595串转并模块使用代码例子 (并口接交通灯)
查看>>
74 HC595 级联控制16 * 16显示屏
查看>>
MFC ListCtrl增加了item,却没有显示
查看>>
ListCtrl插入大量数据时,发现缓慢有问题,QT里有数据和显示分开,MFC也有比较戳的虚拟表,古老的技术
查看>>
MFC如何复制多个文件到剪贴板
查看>>
MFC 高精度计时器
查看>>
大量调用函数,里CImage局部变量 并使用Load函数,会导致大量的线程退出现象解决办法
查看>>
线程的优先级应用场景 - 算法分析计算时间
查看>>
MFC ListCtrl 设置某行没效果解决办法
查看>>
MFC自定义搜索编辑框CEdit,得到焦点提示文本消失,失去焦点,提示文本显示
查看>>
MFC 复制文本到剪贴板
查看>>
CImage 缩放图片
查看>>
树莓派3B+和windows主机方便互传的办法 - 安装samba软件
查看>>
Android调试高德SDK,如何获取SHA1?
查看>>
安卓遇到蓝牙设备发送bug,使用lock加condition解决
查看>>
getScanResults一直为空的解决办法
查看>>
树莓派VNC Viewer连接失败 The connection was refused by the computer
查看>>
linux精确分析函数运行时间
查看>>