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

Okay. I am trying to write a C++ program that reads the contents of a txt file (

ID: 3546620 • Letter: O

Question

Okay.  I am trying to write a C++ program  that reads the contents of a txt file (The words in the dictionary, all lower case) into an array and then not only counts the number of words in that file, but also counts the number of words that begin with the letter c.

Here is what I have for code right now.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

const int Size = 50000;

int main()
{
    int count = 0, count_c = 0;
     
    char start_c;
    ifstream Infile("word_list.txt");
    string word[Size];
    for (int i=0; !Infile.eof(); i++)
      {
        Infile >> word[i];
        count++;
      }
    
    for (int i=0; i<count; i++)
    {
        start_c = word[i].at(0);
           count_c++;
    }
    cout<< "There are " << count << " words in this file" << endl;
    cout << "There are " << count_c << " words beginning with 's' in this file" << endl;
    
    system("PAUSE");
    return 0;
}

     The word count of this program works fine, it's the part where it counts the number of words that start with letter c.  Everything that I have tried has either given me a count of 0 or the program just crashes.  Any ideas?

Explanation / Answer

The for loop is actually not doing anything, what you want is a if condition to check the first letter and see if it begins with c before incrementing. You can actually do that while the readin is being done so you don't have to create that for loop.


#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

const int Size = 50000;

int main()
{
int count = 0, count_c = 0;

char start_c;
ifstream Infile("word_list.txt");
string word[Size];
for (int i=0; !Infile.eof(); i++)
{
Infile >> word[i];
count++;
if(word[i][0] == 'c' || word[i][0] == 'C')
count_c++;
}

cout<< "There are " << count << " words in this file" << endl;
cout << "There are " << count_c << " words beginning with 's' in this file" << endl;

system("PAUSE");
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote