how to do this? write a c++ program that given the name of a text file reads that file and counts the number occurrences of each alphabetic letter in the text. treat upper and lower case instances of a letter as the same letter. hint: look up tolower()---testing the case isn't necessary. if ch is a char, then ch-'a' is a valid c++ expression and will evaluate to 0 when ch is equal to 'a'---try 'b', 'c', and 'd'!)..
really need your help..this is for my case study.

Recommended Answers

All 18 Replies

Break it down into manageable parts. I'd say start by reading the file character by character and simply writing those characters to cout.

Break it down into manageable parts. I'd say start by reading the file character by character and simply writing those characters to cout.

can you give me an example code please?

can you give me an example code please?

Not until you prove that you've done some work yourself. Please read our rules concerning homework.

Not until you prove that you've done some work yourself. Please read our rules concerning homework.

ok here is as far as I got..

#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main( )
{
	char c;
char letter[27];
int count;
ifstream infile;
infile .open("108.txt");
while(! infile.eof())
{
	c=tolower(c);
infile>>letter;
count++;
}
infile.close();
return 0;
}

but it doesn't show how many times the letter occur in the text file. my teacher says that I should use a tolower function, but I don't know where to put it.

well am a beginner in c++ but i see header file for tolower() function should be input #include <ctype.h> which is not present in your program.

i tried but it doesn't work..

OK, you're current program is not going to do what you want it to at all. If I were you, I'd start by looking at the question more carefully and breaking it down into a number of small parts.

So, the question is:

write a c++ program that given the name of a text file reads that file and counts the number occurrences of each alphabetic letter in the text.

So, you can break this down into small bits (without actually writing any c++. Start with this:

int main()
{
   return 0;
}

OK, now add some comments that break down what you think you're going to need to do. So, lets look at the question again:

"write a c++ program that given the name of a text file reads that file and counts the number occurrences of each alphabetic letter in the text"

OK, we're all over that bit, we know we have to use C++! Next bit...

"write a c++ program that given the name of a text file reads that file and counts the number occurrences of each alphabetic letter in the text"

OK, we're going to need to read in a file name and try and open a file with that name, lets add that to our program:

int main()
{
   /* Get file name and try to open file */
   
   return 0;
}

Right, on to the next bit:

"write a c++ program that given the name of a text file reads that file and counts the number occurrences of each alphabetic letter in the text"

OK, so when we have the file name, we're going to have to try and read the file. Let's add that:

int main()
{
   /* Get file name and try to open file */
   
   /* Read file contents into some data structure (probably a std::string) */
   
   return 0;
}

"write a c++ program that given the name of a text file reads that file and counts the number occurrences of each alphabetic letter in the text"

This is kind of a big chunk, but we can add it to our program anyway and break it down later:

int main()
{
   /* Get file name and try to open file */
   
   /* Read file contents into some data structure (probably a std::string) */

   /* Count occurrences of each letter */
   
   return 0;
}

There's a final, implicit part of the question that we haven't added yet: Displaying the results! Lets's add that:

int main()
{
   /* Get file name and try to open file */
   
   /* Read file contents into some data structure (probably a std::string) */

   /* Count occurrences of each letter */

   /* Display results to user */
   
   return 0;
}

Now we can take a look at this skeleton and add more detail to each section. So, first section:

int main()
{
   /* Get file name and try to open file */
      std::string inputFilename;
      // Ask user for a file name
      // Read user's file name into inputFilename
      // Make a std::ifstream object and give it the file name
      // Check that the file opened OK, quit if it didn't
   
   /* Read file contents into some data structure (probably a std::string) */
      std::string allFileContents
      // Until the end of the file...
      //    Read a line from the file (probably using std::getline() )
      //    Add the new line to the end of allFileContents

   /* Count occurrences of each letter */

   /* Display results to user */
      // For each letter of the alphabet...
      //    Print the letter to the screen followed by the count
   
   return 0;
}

Since the /* Count occurrences of each letter */ part is basically the whole problem, I'll leave it to you to break that bit down.

Once you have the plan in individual statements like this, you can start adding code for each step,like this:

int main()
{
   /* Get file name and try to open file */
      std::string inputFilename;
      
      // Ask user for a file name
      std::cout << "Enter a file name:" << std::endl;      

      // Read user's file name into inputFilename
      std::cin >> inputFilename;

      // Make a std::ifstream object and give it the file name
      std::ifstream inFile( inputFilename.c_str(), std::ios::in);
      
      // Check that the file opened OK, quit if it didn't
      if ( ! inFile.is_open() ){
          std::cerr << "Error! Unable to open \"" << inputFilename << "\" for input. Exiting." << std::endl;
          return 1;
      }
   
   /* Read file contents into some data structure (probably a std::string) */
      std::string allFileContents
      // Until the end of the file...
      //    Read a line from the file (probably using std::getline() )
      //    Add the new line to the end of allFileContents

   /* Count occurrences of each letter */

   /* Display results to user */
      // For each letter of the alphabet...
      //    Print the letter to the screen followed by the count
   
   return 0;
}

And so on for the rest of the sections. Once you've done a section, the detailed comments get in the way, so you can go back and remove them, leaving your finished program:

int main()
{
   /* Get file name and try to open file */
      std::string inputFilename;

      std::cout << "Enter a file name:" << std::endl;  
      std::cin >> inputFilename;

      std::ifstream inFile( inputFilename.c_str(), std::ios::in);
      if ( ! inFile.is_open() ){
          std::cerr << "Error! Unable to open \"" << inputFilename << "\" for input. Exiting." << std::endl;
          return 1;
      }
   
   /* Read file contents into some data structure (probably a std::string) */
      std::string allFileContents
      // Until the end of the file...
      //    Read a line from the file (probably using std::getline() )
      //    Add the new line to the end of allFileContents

   /* Count occurrences of each letter */

   /* Display results to user */
      // For each letter of the alphabet...
      //    Print the letter to the screen followed by the count
   
   return 0;
}

Note that I left in the more general, section comment. I find this kind of comment useful, when the aim of a section of program changes from one thing to another. Also, you'll need to include the relevant header files for anything that you use in the actual program (for example, tolower is in <cctype> .

Have fun :)

Use a switch statement

#include<iostream>
#include<fstream>
#include<ctype.h>
#include<sstream>
char ch=tolower(ch-'A');
using namespace std;
int main()
{
	char ch=('a','b','c','d','e','f','g','h','i','j','k','l','M','n','o','P','q','r','s','t','u','v','w','x','y','z');
	fstream infile;
	infile.open("108.txt");

	if(ch =='A' || ch =='Z')
	{
	cout<<ch-'A';
	}
	else if(ch =='a' || ch =='z')
	{
cout<<ch-'a';
	}
	while(!infile.eof())
	{
		
		cout<<ch-'a';
	
	
		infile>>ch;	
	}
	
	infile.close();
	return 0;
}

send me the codes please? i can't get the output that my teacher wants..this is my email [email erased] i would really appreciate your help..i will pass this case study today..so please help me...

OK, I think that you're missing a vital piece of information that you're given in the question. ASCII is a widely used (look it up) set of rules about how text (specifically Roman characters) is represented in computers. In ASCII the letters 'a' to 'z' and 'A' to 'Z' are converted a continuous set of numbers when you convert them from char to int . This means that you can do things like this:

char c = 'd';
int x = c - 'a';

here, x will have the value of 3. I think in ASCII 'a' = 80, so 'b' = 81, 'c' = 82, 'd' = 83, 'e' = 84, etc. So 'd' - 'a' is equivalent to 83 - 80 = 3. You see?

If you have a capital letter then you will be doing something like 'E' - 'a', which will give you a number that's not in the range 0 - 25. This is where the tolower() function comes in. If you do, std::tolower( 'E' ) - 'a' you'll get the desired answer of 4.

So, what if you want to decide if you have a character that is a letter? Well, you just need to check that the character (after you've used tolower ) is greater than or equal to 'a' and less than or equal to 'z'. If it's not in this range you can skip it and move on to the next character.

If I were you I would start your program over, after reading this post and the previous one I made and see where you get to. To illustrate why, I'll convert your program into the kind of comment-code that I posted before, so you can see how far out you are:

int main()
{
   /* Open a file */
   //   You didn't check if it actually opened
   
   /* If the character is 'A' or 'Z', print the character minus 'A' */
   // Note that even if your code compiled, ch is undefined at this point, so this will give an unknown result
   
   /* Else, if the character is 'a' or 'z', print the character minus 'a'*/
 
   /* until the end of the file... */
   //    Print the character minus 'a'
   //    Get a token from the file and convert it to a char, store it in ch

   /* Close the file */
 
   return 0;
}

Does this seem like it is going to do what you want?

A somewhat minor nit-pick:

In ASCII the letters 'a' to 'z' and 'A' to 'Z' are converted a continuous set of numbers when you convert them from char to int .

Letters are not converted to numbers, they are numbers. 66 is a number, and if output as a character value, it simply gets displayed as 'B'. If output as an integer, it gets displayed as 66.

the output of my program is the number of letters in the text file..but if it read a big letter 'A' and small letter 'a' the program should read it as 1,that big letter A and a are the same

OK, I think that you're missing a vital piece of information that you're given in the question. ASCII is a widely used (look it up) set of rules about how text (specifically Roman characters) is represented in computers. In ASCII the letters 'a' to 'z' and 'A' to 'Z' are converted a continuous set of numbers when you convert them from char to int . This means that you can do things like this:

char c = 'd';
int x = c - 'a';

here, x will have the value of 3. I think in ASCII 'a' = 80, so 'b' = 81, 'c' = 82, 'd' = 83, 'e' = 84, etc. So 'd' - 'a' is equivalent to 83 - 80 = 3. You see?

If you have a capital letter then you will be doing something like 'E' - 'a', which will give you a number that's not in the range 0 - 25. This is where the tolower() function comes in. If you do, std::tolower( 'E' ) - 'a' you'll get the desired answer of 4.

So, what if you want to decide if you have a character that is a letter? Well, you just need to check that the character (after you've used tolower ) is greater than or equal to 'a' and less than or equal to 'z'. If it's not in this range you can skip it and move on to the next character.

If I were you I would start your program over, after reading this post and the previous one I made and see where you get to. To illustrate why, I'll convert your program into the kind of comment-code that I posted before, so you can see how far out you are:

int main()
{
   /* Open a file */
   //   You didn't check if it actually opened
   
   /* If the character is 'A' or 'Z', print the character minus 'A' */
   // Note that even if your code compiled, ch is undefined at this point, so this will give an unknown result
   
   /* Else, if the character is 'a' or 'z', print the character minus 'a'*/
 
   /* until the end of the file... */
   //    Print the character minus 'a'
   //    Get a token from the file and convert it to a char, store it in ch

   /* Close the file */
 
   return 0;
}

Does this seem like it is going to do what you want?

what do you mean my "Get a token from the file and convert it to a char, store it in ch
"?

the output of my program is the number of letters in the text file..but if it read a big letter 'A' and small letter 'a' the program should read it as 1,that big letter A and a are the same

So add the number of 'A' and 'a' together before you print out the value.

what do you mean my "Get a token from the file and convert it to a char, store it in ch
"?

A token is a "chunk" of stuff from the file. In this case, it's going to go to the file and get everything from the first non-white-space character (white-space is any of space, tab, carriage return, etc) to the next white-space character. So, if your text file looks like this: The quick brown fox jumps over a lazy dog When you do infile >> ch it will get the first token, "The" in this case, and try and convert it to a char . This will probably fail, since there's no obvious way to convert a string of chars to a single char

the output of my program is the number of letters in the text file..but if it read a big letter 'A' and small letter 'a' the program should read it as 1,that big letter A and a are the same

This is no problem:

std::string text("The quick brown fox jumps over the lazy dog");
unsigned numberOfAs = 0;

for ( unsigned i = 0; i < text.length; ++i )
{
   if ( text[i] == 'A' || text[i] == 'a' )
      ++numberOfAs;
}

std::cout << "There were " << numberOfAs << " A's or a's in the text" << std::endl;

This is only counting the 'A' or 'a' chars, you will need a slightly different version to count all the chars.

will you please tell me what will be the procedure for strings(for same purpose) in c++
i m trying this

#include <vector>
#include <iostream>
#include <cstdio>

int main()
{
    //setup
    std::vector<int> alphabetCount;

    for (int i = 0; i < 26; ++i)
    {
        alphabetCount.push_back(0);
    }

    //now the interactive bit
    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']; //subtract a, so if currentChar = a, 'a' - 'a' = 0, so its index 0
        }
    }

    for (size_t i = 0; i < alphabetCount.size(); ++i)
    {
        std::cout << "there were " << alphabetCount[i] << " occurences of " << static_cast<char>(i + 'a') << "\n"; //add 'a' for the same reason as above, though we have to cast it to a char.
    }
system("pause");
    return 0;
}

but it only returns values from single string i want result from all string

@Hafiz ... welcome to Dani's.

Please note:
the post you added to was already 4 years old ...
so best to start your own new thread.

And it's generally a good idea to NOT 'hijack' another persons post ...
so please start you own new thread if you want more help.

You do not need here to include <cstdio.h>
// Note: <stdio.h> is typically for C code //

What you need to include is <cctype> // re. tolower, isalpha //

And to keep code portable, not good to use system calls ... so ...
you may like to see this revision:

// countRepeatCharsInString.cpp //

#include <iostream>
#include <cctype> // re. tolwer, isalpha

const int NUM_LETS = 26;



int main()
{
    // initial all to 0 //
    int count[NUM_LETS] = { 0 }; // this is all that's needed here

    //now the interactive bit
    std::cout << "Enter a line of text : " << std::flush;
    std::string line;
    std::getline( std::cin, line );

    for( size_t i = 0; i < line.size(); ++ i )
    {
        int curChar = tolower( line[i] ); // letters "are int's" in C/C++ //
        if( isalpha(curChar) )
        {
            ++ count[curChar - 'a']; // get int in range 0..25 //
        }
    }

    for( size_t i = 0; i < NUM_LETS; ++ i )
    {
        if( count[i] ) // just show counts of letters that are there //
            std::cout << "There were " << count[i]
                      << " occurences of " << static_cast< char >(i + 'a')
                      << "\n"; //add 'a' for the same reason as above, though we have to cast it to a char.
    }

    std::cout << "Press 'Enter' to continue/exit ... " << std::flush ;
    std::cin.get();
    return 0;
}

Note:
you do not need to have in the above code std::flush;
I just personally like to explicity show that it is to happen 'now' ... not later.
`

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.