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

标签 c++ string count

我的类作业是编写一个代码,该代码将计算 .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/

相关文章:

c++ - 评估宏中传递的参数

c++ - 如何使用所有者 CMFCTabCtrl 类在子 Clistbox 中设置颜色

bash - 从 bash 映射中检索时如何区分 null 和空字符串

python - 由字符串组成的 numpy 数组的连接函数

Javascript Regex - 替换所有出现的匹配字符串,除了括号之间的任何字符串

c# - 如何在不混淆的情况下监视用户对 .NET Web 浏览器控件的操作?

python - 如何使用ctypes(C++到Python)将opencv3 cv::Mat转换为numpy数组?

python - 为什么 str.count ('' ) 和 len(str) 给出不同的输出?

mysql - 为什么我的`sql_calc_found_rows`比MySQL中的`count(*)`要快?

mysql - 具有重复项的总行数