【发布时间】:2017-02-10 22:43:05
【问题描述】:
我的班级任务是编写一个代码,该代码将计算.txt 文件中特定单词的出现次数不区分大小写
int main(){
char U[50];
string a;
int number=0;
cout<<"name of file"<<endl;
cin.getline(U,50);
ifstream text(U,ios_base::binary);
if(!text){
cout<<"nonexisting"<<endl;
return 0;
}
cin>>a;
transform(a.begin(), a.end(), a.begin(), ::tolower);
string word;
while(text>>word){
transform(word.begin(), word.end(), word.begin(), ::tolower);
if(!a.compare(word))number++;
}
cout<<number;
text.close();
return 0;
}
问题是程序在一个文件中计算了 32 个字,但其中有 40 个
这是我解决问题的方法
int main(){
char U[50];
string a;
int number=0;
cout<<"name of file"<<endl;
cin.getline(U,50);
ifstream text(U);
if(!text){
cout<<"nonexisting"<<endl;
return 0;
}
cin>>a;
transform(a.begin(), a.end(), a.begin(), ::tolower);
string word;
while(text>>word){
transform(word.begin(), word.end(), word.begin(), ::tolower);
if (word.find(a) != string::npos)number++;
}
cout<<number;
text.close();
【问题讨论】:
-
对于初学者来说,如果你想计算一些东西,你可能应该使用
std::countorstd::count_if。要继续,我建议将所有单词读入std::vector(可以一次性完成,无需循环)。可能无法解决您的问题,但会使代码更简单。 -
至于你的问题,你为什么要以二进制模式打开一个文本文件?这可能是一个问题。
-
lapsus calami 我之前的作业是二进制的,所以是个错误,不,它不能解决问题,但感谢建设性的批评
-
显示一个无法正确计数的文件。