C++ Program to Count Occurrence of a Word in a Text File

C++ program will read a word from the user and then count its total occurrence in a text file “my_data.txt”. Make sure you have already create this text file and have some text in it. Place this file in the same directory where your program source file is present.

C++ Program to Count Occurrence of a Word in a Text File

#include <vector>
#include <iostream>
#include <cstdio>
int main()
{
    std::vector<int> alphabetCount;
    for (int i = 0; i < 26; ++i)
    {
        alphabetCount.push_back(0);
    }
    std::cout << "Enter a line of text\n";
    std::string line;
    std::getline(std::cin, line);
    for (size_t i = 0; i < line.size(); ++i)
    {
        char currentChar = tolower(line[i]);
        if (isalpha(currentChar))
        {
            ++alphabetCount[currentChar - 'a']; 
        }
    }
    for (size_t i = 0; i < alphabetCount.size(); ++i)
    {
        std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "\n";
    }
system("pause");
    return 0;
}

Output of Program

Enter a line of text
CodeBlah
there were 1 occurences of a
there were 1 occurences of b
there were 1 occurences of c
there were 1 occurences of d
there were 1 occurences of e
there were 0 occurences of f
there were 0 occurences of g
there were 1 occurences of h
there were 0 occurences of i
there were 0 occurences of j
there were 0 occurences of k
there were 1 occurences of l
there were 0 occurences of m
there were 0 occurences of n
there were 1 occurences of o
there were 0 occurences of p
there were 0 occurences of q
there were 0 occurences of r
there were 0 occurences of s
there were 0 occurences of t
there were 0 occurences of u
there were 0 occurences of v
there were 0 occurences of w
there were 0 occurences of x
there were 0 occurences of y
there were 0 occurences of z