读取文件内容的时候需要判断内容是否是中文,同时有可能还需要判断是否带有中文标点符号,这里简单说明一下识别方法。
直接上代码:
#include#include #include #include #include bool readFile(std::string strPath) { int nNormal; int nFormatErr; std::string strLine; // 文件路径为空. if (strPath.empty()) { //file path is empty return false; } // 打开文件 ifstream fp(strPath.c_str(), ios::in); if (fp.fail()) { //file open failed; return false; } //解析文件 while (getline(fp, strLine)) { //格式校验 if (!Check(strLine)) { //格式错误 nFormatErr++; } } fp.close(); return true; } bool Check(const std::string strContent) { UINT16 i; std::wstring wstrContent; //将内容转换为宽字符 wstrContent = string2wstring(strContent); for (i = 0; i < wstrContent.length(); i++) { if ((UINT16)wstrContent[i] > 0x80) { //宽字符 if ((iswpunct(wstrContent[i])) || (iswspace(wstrContent[i]))) { return false; } } else { //ASCII if ((wstrContent[i] > '0') || (wstrContent[i] < '9') || (ispunct(wstrContent[i]))) { return false; } } } return true; } std::string wstring2string(std::wstring wstr) { std::string result; int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL); if (len <= 0)return result; char* buffer = new char[len + 1]; if (buffer == NULL)return result; WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL); buffer[len] = ' '; result.append(buffer); delete[] buffer; return result; } std::wstring string2wstring(std::string str) { std::wstring result; int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0); if (len < 0)return result; wchar_t* buffer = new wchar_t[len + 1]; if (buffer == NULL)return result; MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len); buffer[len] = ' '; result.append(buffer); delete[] buffer; return result; }
wstring2string 和 string2wstring 是常规的一个wstring和string的转换函数,网上也有很多类似的,就不多说。
这里判断符号主要用到几个关键函数。
iswpunct(wint_t ch)
用于检查传递的宽字符是否为标点符号。如果不是标点符号,则返回零,否则返回非零值。
需要声明 “cwctype”头文件。
iswspace(wint_t ch)
检查宽字符是否为空格,在头文件“wctype.h”中。
如果宽字符是空白字符,则为非零值,否则为零。
int ispunct(int c)
检查参数c是否为标点符号或特殊符号。返回TRUE也就是代表参数c为非空格、非数字和非英文字母。
头文件: c--
c++ -- 若参数c为标点符号或特殊符号,则返回TRUE,否则返回NULL(0)。


![[C/C++] 如何判断文件内容是否带中文标点符号 [C/C++] 如何判断文件内容是否带中文标点符号](http://www.mshxw.com/aiimages/31/1026905.png)
