gpt4 book ai didi

c++ - 计算特定单词在 C++ 文本文件中出现的次数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:44:22 25 4
gpt4 key购买 nike

我的类作业是编写一个代码,该代码将计算 .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/ , >> 运算符使用空格作为分隔符进行解析。

关于c++ - 计算特定单词在 C++ 文本文件中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42169826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com