Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the function charCnt. charCnt is passed in a name of a file and a sing

ID: 3661787 • Letter: I

Question

Implement the function charCnt. charCnt is passed in a name of a file and a single character (type char). This function should open the file, count the number of times the character is found within the file, close the file, and then return the count.

If the file does not exist, this function should output an error message and then call the exit function to exit the program with an error value of 1.

USE THIS CODE TEMPLATE PLEASE

#include <fstream>
#include <iostream>
#include <cstdlib>

using namespace std;

// Place charCnt prototype (declaration) here


int main() {
string filename;
char ch;
cout << "Enter the name of the input file: ";
cin >> filename;
cout << "Enter a character: ";
cin >> ch;

cout << "# of " << ch << "'s: " << charCnt(filename, ch) << endl;

return 0;
}

// Place charCnt implementation here

Explanation / Answer

countCharactetr.cpp

// Enter the complete path with filename otherwise if you wan't to enter just the filename then adjust the code //accodingly by pasting your text file at default path or using a particular constant location for the file and harcode //that in the code.

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

int charCnt(string filename, char ch);

int main() {
   string filename;
   char ch;
   cout << "Enter the name of the input file: ";
   cin >> filename;
   cout << "Enter a character: ";
   cin >> ch;

   cout << "# of " << ch << "'s: " << charCnt(filename, ch) << endl;

   return 0;
}

int charCnt(string filename, char ch)
{
   int count = 0;
   ifstream infile(filename);

   if (!infile.is_open())
   {
       cout << "Error opening file ";
       exit(1);
   }
   else
   {
       char c;
       infile.get(c);
       while (!infile.eof())
       {
           if (c == ch)
           {
               count++;
           }
           infile.get(c);
       }
   }
   infile.close();
   return count;
}