Moffet
Moffet

Reputation: 19

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

This is my code that counts the occurences of a particular string in a file.

#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;
}

The file is provided in the root of the project. The problem is that I'm getting 0 for any word being counted.

Upvotes: 0

Views: 2852

Answers (2)

Ziezi
Ziezi

Reputation: 6477

With a few small corrections your code will do the job, specifically the file reading loop could be modified to firstly read a whole line and then read each string contained in it separately:

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;
}

Few notes:

  • you don't need to explicitly close your file stream, it is done automatically at the end, as file is a local variable in the function.

  • the try - catch block is redundant if you are only using it to check stream status. You could do it with a single line, as pointed out in the answer.

  • it is a good practice for the file name to be a c - style string (ending with '\0'). Stream member function c_str() performs the conversion.

  • you could open the file in the definition of the stream and skip the line containing the stream member function open().

Upvotes: 0

Matt
Matt

Reputation: 2802

I changed from file.open(file_name); to file.open(file_name.c_str()); and it worked fine.

 $ cat file.txt
 hello
 good bye

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

ifstream takes a c-string as an input, not a string. To catch make sure the file is open before reading with:

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

Upvotes: 2

Related Questions