最近用MFC编Bayes文本分类器,需要将停用词从txt文件中依次读出来(每行一个词),用其本身的CStdioFile类的ReadString函数虽然可以一行一行读入文本,但到程序中就成了乱码,采用一些编码转换方法都未能解决问题。
后来,我干脆直接采用ifstream读文件,一个字符一个字符的读入文本,并通过比对'/n'判断是否换行。最后,再通过c_str函数和CString的构造函数将std::string转化成MFC的CString。
完整的代码如下:
StopWord::StopWord()
{
CString stopListPath = _T(".//Data//ChineseStopList.txt");
ifstream fcin;
fcin.open(stopListPath);
char c;
string str;
while(fcin.read(&c,sizeof(char)))
{
if(c == '/n')
{
if(!str.empty())
{
CString stopWord(str.c_str());
//添加自己的相关代码...
str.clear();
}
}
else
{
str += c;
fcin.read(&c,sizeof(char));
str += c;
}
}
}