i need to write a program that can count the number words the user enters and and the recurences of each letter.

ex: Have a nice day
Total words: 4
a = 3
d = 1
e = 2
...

Can't get the program i've writen so far to count the number of words.

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;


int main()
{

  char letters[] = "abcdefghijklmnopqrstuvwxyz";
  int freq[sizeof letters - 1] = {0};
  char text[60];
  char input;
  int numWords=0;
  bool inword = false;
  cout<<"Enter a line of text: \n";
  cin>>input;
    while((input=cin.get()) !='\n')
    { // Counts the number of words in the text.
        if(input == ' ' || input== '\t')
        {
            inword = false;
        }
        else if (inword == false)
        {
            inword = true;
            numWords++;
        }

        cout<<"The number of words in the text is: "<<numWords<<endl;

        if ( cin.getline ( text, sizeof text ) ) 
        { 
            for ( int i = 0; text[i] != '\0'; i++ ) 
            {// Converts all letters to lower case.
            if ( isalpha ( text[i] ) )
                ++freq[tolower ( text[i] ) - 'a'];
            }

            for ( int i = 0; letters[i] != '\0'; i++ ) 
            {// Counts the frequency of all letters.
            if ( freq[i] != 0 )
                cout<< letters[i] <<": "<< freq[i] <<endl;
            }
        }

    }
  return 0;
}

thanks...

sizeof letters: needs brackets around letters, but that could be the absence of code tags (use [xCODE]paste code here[x/CODE] --> remove x's wen u post: i put that in so u could see the tags!!)
when initialiseing the frequency table you would need to set every element to zero to be sure, you have only set the first. using a loop is a much better idea.

have you tried cout'ing input back to the console to check the RIGHT chars are going in?? i have been through the loop a few times in my head and have tested it like so

#include <iostream.h>

int main(void)
{

    bool inword = 0;
    unsigned int numwords = 0;
    char *str = "this is a test     string   \t   \n"; // 5 words....
    char letter; // comparison letter

    while (letter = *str++)
    {
        if(letter == ' ' || letter == '\t' || letter == '\n') 
        {
            inword = 0;
        }
        else if(inword == 0)
        {
            inword = 1;
            numwords++;
        }
    }
    cout << "Found " << numwords << " words!\n"; // it works!!
    return 0;
}

This counter works, so your code should... using this code will get you the number of words, see if you can get it working and post back with any results. hope this helps :)

sizeof letters: needs brackets around letters

No, you don't. You need parentheses for a type, but not an object.

when initialiseing the frequency table you would need to set every element to zero to be sure, you have only set the first. using a loop is a much better idea.

Wrong again. The remainder of the array is also initialized to zero. Using a loop is not a better idea.

The remainder of the array is also initialized to zero. Using a loop is not a better idea

Sorry its just a habit. Have done it with character strings and had junk data in each one. Playing it safe.

You need parentheses for a type, but not an object.

News to me, i always use brackets, then i dont forget. :)#

BTW: I tried your code chriswell, the cin.get() line seems to miss the first word (if you cout the input). I thought if you cout input you should get the same line you entered in, but when i tried it failed. It seems this is the critical flaw.

i need to write a program that can count the number words the user enters and and the recurences of each letter.

What you had was mostly there, you just had some things misplaced and tried to get user input too many times.

#include <iostream>
#include <cctype>
using namespace std;

int main()
{

   char letters[] = "abcdefghijklmnopqrstuvwxyz";
   int  freq[sizeof letters - 1] = {0};
   char text[60];
   int  numWords = 0;
   bool inword = false;
   cout<<"Enter a line of text: \n";
   if ( cin.getline ( text, sizeof text ) )
   {
      for ( int i = 0; text[i] != '\0'; i++ )
      {// Converts all letters to lower case.
         if ( isalpha ( text[i] ) )
         {
            ++freq[tolower ( text[i] ) - 'a'];
         }
         // Counts the number of words in the text.
         if ( [B]isspace(text[i])[/B] )
         {
            inword = false;
         }
         else if ( inword == false )
         {
            inword = true;
            numWords++;
         }
      }
      for ( int i = 0; letters[i] != '\0'; i++ )
      {// Counts the frequency of all letters.
         if ( freq[i] != 0 )
            cout<< letters[i] <<": "<< freq[i] <<endl;
      }
   }
   cout<<"The number of words in the text is: "<<numWords<<endl;
   return 0;
}

Have done it with character strings and had junk data in each one. Playing it safe.

I doubt you can show me an example. Unitialized arrays will "contain junk". Initialized arrays are different.

something like this

char text[256] = "1o0oBhP";

Most of the time its ok and the rest is blank. Occasionally its not and causes errors when you use strcat and other string functions. I recently had the same problem on a small log project using mainly fstream and strcat. Playing it safe. I realise numericals are initialised zero but i have seen in the past cout giving scientific numbers. Ive dealt with enough random errors that i always make sure everything is concrete.

Most of the time its ok and the rest is blank. Occasionally its not and causes errors when you use strcat and other string functions.

I would suspect the use of strcat, not the initialization.

Playing it safe. I realise numericals are initialised zero but i have seen in the past cout giving scientific numbers. Ive dealt with enough random errors that i always make sure everything is concrete.

Learn to capitalize on these errors and find the real reasons. Otherwise you may be burying bugs deeper.

fair enough. Im used to Programming in VB (6 years and before i learned c++) where you can observe variables at run time (ie wats in the string). however my c++ IDE doesnt.... so i dont know what is going on i have to make certain nothing can go wrong :(
Do you use Dev-C++? I have 4.9.9.0 and if anyone knows how can i observe vaiables at run time??

Do you use Dev-C++? I have 4.9.9.0 and if anyone knows how can i observe vaiables at run time??

I have Dev-C++, but don't use it much. I think there is a way and seem to remember something about gdb, but I'm not familiar with its use.

I just tend to use output statments to see values at runtime ("debugging with printf").

#include <stdio.h>
#include <ctype.h>

int main(void)
{
   char text [ 20 ] = "Hello world\n";
   size_t i;
   for ( i = 0; i < sizeof text; ++i )
   {
      printf ( "text[%2d] = ", i );
      printf ( isprint ( text [ i ] ) ? "'%c'" : "%d", text [ i ] );
      putchar( '\n' );
   }
   return 0;
}

/* my output
text[ 0] = 'H'
text[ 1] = 'e'
text[ 2] = 'l'
text[ 3] = 'l'
text[ 4] = 'o'
text[ 5] = ' '
text[ 6] = 'w'
text[ 7] = 'o'
text[ 8] = 'r'
text[ 9] = 'l'
text[10] = 'd'
text[11] = 10
text[12] = 0
text[13] = 0
text[14] = 0
text[15] = 0
text[16] = 0
text[17] = 0
text[18] = 0
text[19] = 0
*/

fair enough. Im used to Programming in VB (6 years and before i learned c++) where you can observe variables at run time (ie wats in the string). however my c++ IDE doesnt.... so i dont know what is going on i have to make certain nothing can go wrong :(
Do you use Dev-C++? I have 4.9.9.0 and if anyone knows how can i observe vaiables at run time??

Console debugging has problems with old Windows and Dev C++ versions. You should be okay with version 4.9.9.0
Here is the poop:
Debugging with Dev C++:
Make sure you are using a project!
Go to Project Options > Compiler > Linker and set Generate Debugging Information to yes. Make sure you are not using any optimization options or the strip option!!!
Now do a full rebuild with Ctrl-F11, then set breakpoints where you want the debugger to stop. To set a breakpoint on a line, put your cursor on the line and press Ctrl-F5 (or click on the gutter left of the line). You can add or remove breakpoints during the debug session, but need to have at least one to start with.
Launch the debugger clicking the debug button (or F8). The program stops at the first breakpoint. You can step through the code and enter function calls, by clicking on the "step into" button (or Shift-F7), or stepping over the function calls, by clicking the "next step" button (or F7). To go to the next breakpoint click the "continue" button (or Ctrl-F7).
When the program is at a breakpoint, and you are stepping through the code, you can display the values of various variables in your program by putting your mouse over the variable name. You can also display variables and expressions by pressing the "add watch" button (or F4) and typing the expression.
This info should be in the help included with Dev-C++.

I do prefer Dave's way of run-time debugging, just offset the code a little so you can remove it later.

commented: Thank you very much for that! --Dave +1

Back to the question at hand.
You can implement a frequency table via the binary search tree that is the basis of map from the Standard Template Library. There was a code sample posted by Narue on this very merry forum not too long ago.

cheers vega, i overcame the problem in the end anyway using an html logfile -> easier to read and break up into tables for arrays ect...

What is the problem (if any) with the frequency counter?? looks ok at first glance, hows the project going chriswell? Would be interested to see if you got the whole source working correctly!

I know that this is way late but just found this site and this IS a program that our company is interested in... actually, we have a similiar program already in use but it was written way back and we are hoping to upgrade the system that the program is on.

The counter currently works on a Win98SE with an LPT 1 direct line to an Epson dot matrix printer. Have tried it on WinXP Pro and no go. So this is one item that is holding us back.

Has anyone found or written this type of program?

bg

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.