[英]Count number of appearances of a specific word in a C++ text file
我分配给班级来编写代码,该代码将计算不区分大小写的.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();
我的猜测是,不计算在内的8个单词的末尾都有换行符,即它们出现在文件的行尾。 你能检查一下是不是这种情况? 根据http://www.cplusplus.com/reference/string/string/operator%3E%3E/ ,>>运算符使用空格作为分隔符进行解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.