用C++计算一个单词在文件中的出现次数

Counting the occurances of a word in a file in C++

本文关键字:文件 单词 计算 C++ 一个      更新时间:2023-10-16

这是我的代码,用于统计文件中特定字符串的出现次数。

#include <iostream>
#include <string>    
int frequency(std::string s, std::string file_name){
    std::ifstream file;
    std::string word;
    int count = 0;
    try{
        file.open(file_name);
        while(file>>word){
           if(s.compare(word) == 0) ++count;
        }
        file.close();
    }catch(std::ifstream::failure e){
        //std::cout<<e<<std::endl;
    }
    return count;
}
//===============================================
int main() {
    std::string file_name, word;
    std::cout << "Enter file name.." << 'n';
    std::cout << "Enter word.. " << 'n';
    std::cin >> file_name >> word; 
    int count = frequency(word, file_name);
    std::cout << "Occurrences of " << word << ": " << count;
    return 0;
}

该文件在项目的根目录中提供。问题是,对于任何正在计数的单词,我都会得到0

我从file.open(file_name);更改为file.open(file_name.c_str());而且效果很好。

 $ cat file.txt
 hello
 good bye
 $ a.out
Enter file name..
Enter word..
file.txt
hello
Occurances of hello: 1

ifstream将c字符串作为输入,而不是字符串。要捕获,请确保文件在读取之前已打开:

if (file.is_open()){
   ... do stuff....
else
   ... error 

通过一些小的更正,您的代码就可以完成这项工作,特别是文件读取循环可以被修改为首先读取整行,然后分别读取其中包含的每个string

int frequency(std::string s, std::string file_name) {
    std::ifstream file(file_name.c_str());
    // check if file successfully open
    if (!file) cerr << "Can't open input file!n";
    int count = 0;
    try{
        // extract all lines
        std::string line;
        while(getline(file, line)) {
            stringstream ss(line);
            string word;
            // extract all words separated by white space
            while (ss >> word) {
                // compare with wanted
                if(s == word) ++count;
           }
        }
    }catch(std::exception& e){
        // std::cout << e.what() << std::endl;
    }
    return count;
}

注意事项:

  • 您不需要显式关闭文件流,这是在最后自动完成的,因为file是函数中的局部变量。

  • 如果仅使用try-catch块来检查流状态,则该块是冗余的。正如答案中所指出的,你可以用一行字来完成。

  • 文件名最好是c风格的字符串(以"\0"结尾(。流成员函数c_str()执行转换。

  • 您可以在流的定义中打开文件,并跳过包含流成员函数open()的行。