C++ Program to Print Occurrence of Characters from ‘a’ to ‘z’ in a Given File

This C++ Program which prints occurence of characters from ‘a’ to ‘z’ in an Input File. The program creates an input file stream, goes through each character in every line of the file stream and increments each character’s count on every encounter of the specific character.

Here is source code of the C++ program which prints occurence of characters from ‘a’ to ‘z’ in an Input File. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Print Occurence of Characters from 'a' to 'z' in an Input File
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <fstream>
  7. #include <cctype>
  8.  
  9. int main()
  10. {
  11.     int arr[26];
  12.     std::ifstream file("test.cpp");
  13.     std::string str;
  14.  
  15.     for (int i = 0; i < 26; i++)
  16.     {
  17.         arr[i] = 0;
  18.     }    
  19.     while (getline(file, str))
  20.     {
  21.         int i = 0;
  22.         while (str[i] != '\0')
  23.         {
  24.             if (isalpha(str[i]))
  25.                 arr[(str[i] - 'a')]++;
  26.             i++;
  27.         }
  28.     }
  29.     std::cout << "Count of character \'a\' - \'z\'\n";
  30.     for (int i = 0; i < 26; i++)
  31.     {
  32.         char c = 'a' + i;
  33.         std::cout << c << " " << (arr[i] + '0') << "\t";
  34.         if ((i + 1) % 6 == 0)
  35.             std::cout << std::endl;
  36.     }
  37.     std::cout << std::endl;
  38.     file.close();
  39. }

$ g++ main.cpp
$ ./a.out
Count of character 'a' - 'z'
a 65    b 48    c 65    d 62    e 68    f 58
g 52    h 53    i 86    j 48    k 48    l 62
m 53    n 65    o 60    p 52    q 48    r 73
s 69    t 83    u 57    v 48    w 50    x 48
y 49    z 49

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.