Thread: Word Count PlS HELP

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    15

    Word Count PlS HELP

    ok here is my code and the txt file contians
    the dog goes bark
    the cat goes meow

    i would like to count the words but i have no clue how ??? can anyone help ??? i know i should know how to do this but i'm pointless and clueless on how to complete this task.... here is my code
    Code:
    #include <iostream.h>
    #include <fstream.h>
    #include "tstring.h"
    
    
    class WordCount
    {
    	private:
              String word;
              ifstream infile;
              int count;
    
       public:
       	void ReadStr();
          void WriteStr();
         	int CountWords();
    
    };
    
    void WordCount::ReadStr()
    {
       infile.open("test.txt");
    
    getline(infile, word, '\n'); //read first line of file
    
    }
    
    
    void WordCount::WriteStr()
    {
    
    cout << word << endl; //display first line of file
    
    while(getline(infile, word, '\n')) //read each line file one at a time
    {
    cout << word << endl; //displaying them as you go
    }
    
    
     }
    
     int WordCount::CountWords()
    {
    count = ' ';
    while(infile >> word)
    {
    
    count++;
    }
    
    
        cout << "The number words in the program are " << count << endl;
    
    
     }
    
    
    int main()
    {
    WordCount WC;
    char res;
    
    
    do
    {
    	cout << "1 Read String." << endl;
       cout << "2 Print String." << endl;
       cout << "3 Count Words." <<endl;
       cout << "4 Exit." << endl;
       cout << "Please Select an operation: " << endl;
    
    cin >> res;
    
    switch(res)
    {
    case '1':
       		WC.ReadStr();
             break;
    case '2':
    			WC.WriteStr();
             break;
    case '3':
    			WC.CountWords();
             break;
    case '4':
             cout << "Thanks for using my program." << endl;
    			exit(1);
    			break;
    default:
    	cout << "Invaild Option... Please Try again " << endl;
    }
       } while(res!='4');
    }
    Please help I need it desperatley...

  2. #2
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    You should use the overloaded version of getline:

    Code:
    ifstream infile("test.txt");
    char s[ 256 ];
    
    while (infile.getline( s, 255, ' ' ))
        cout << s << endl;
    
    infile.close();
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    15
    ok that does nothing

  4. #4
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Hmm, it should have printed each of the words in test.txt, one per line. Worked fine on my machine...when you say it does nothing what do you mean...absolutely no output? Error messages? Failed to compile?
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  5. #5
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    infile.getline( s, 255, ' ' )

    will work for Cstyle strings but not for STL strings or members of the Sting class. Also this line will only read up to the first space, meaning one word which may or may not be same as one line. Use the newline char as the terminating character if you want to read one line at a time.

    try:

    getline(infile, s, '\n')

    to read all characters, space and all, up to the first newline char, into an STL string called s or a member of your String class called s.

    void WordCount::WriteStr()
    {

    cout << word << endl; //display first line of file

    //only if there is something in word to begin with!!!
    //call getline(infile, word, '\n') before this line to be sure there is something in word

    while(getline(infile, word, '\n')) //read each line file one at a time
    {
    cout << word << endl; //displaying them as you go
    }


    to count the number of words in the file use the version I wrote before using >>. declare an int variable local to the method called count and initialize it to 0. After you read the firt word increment count by one. Then each time through the loop increment count by one again. You probably don't even need the call to >> outside the loop if you use the call to >> as the conditional of the loop.


    int count = 0;
    while(infile >> word)//read each word one at a time
    {
    cout << word << endl; //display each word one per line
    count++;//count each word one at a time
    }
    cout << count;//what was count when loop is done

    should do it.


    if you want to count the number of lines (where line is defined as a string terminated by a newline character) do the same thing in the version with getline().

  6. #6
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Wow...I hadn't realized that >> would break the input along whitespace boundaries anyway...teaches me for programming too much in Perl recently (and not trying the simplest solution first...I f*****g hate char *'s).

    Thanks for setting me straight.
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  7. #7
    Registered User
    Join Date
    Sep 2002
    Posts
    15
    Ok here is the code so far
    Code:
    #include <iostream.h>
    #include <fstream.h>
    #include "tstring.h"
    
    
    class WordCount
    {
    	private:
              String word;
              ifstream infile;
              int count;
    
       public:
       	void ReadStr();
          void WriteStr();
         	int CountWords();
    
    };
    
    void WordCount::ReadStr()
    {
       infile.open("test.txt");
    
    getline(infile, word, '\n'); //read first line of file
    
    }
    
    
    void WordCount::WriteStr()
    {
    
    cout << word << endl; //display first line of file
    
    while(getline(infile, word, '\n')) //read each line file one at a time
    {
    cout << word << endl; //displaying them as you go
    }
    
    
     }
    
     int WordCount::CountWords()
     {
     count = 0;
    while(infile >> word)//read each word one at a time
    {
    cout << word << endl; //display each word one per line
    count++;//count each word one at a time
    }
    cout << count<<  endl;//
    
    
     }
    
    
    int main()
    {
    WordCount WC;
    char res;
    
    
    do
    {
    	cout << "1 Read String." << endl;
       cout << "2 Print String." << endl;
       cout << "3 Count Words." <<endl;
       cout << "4 Exit." << endl;
       cout << "Please Select an operation: " << endl;
    
    cin >> res;
    
    switch(res)
    {
    case '1':
       		WC.ReadStr();
             break;
    case '2':
    			WC.WriteStr();
             break;
    case '3':
    			WC.CountWords();
             break;
    case '4':
             cout << "Thanks for using my program." << endl;
    			exit(1);
    			break;
    default:
    	cout << "Invaild Option... Please Try again " << endl;
    }
       } while(res!='4');
    }
    and the out put i get for the count is 0.. ? wtf ?? I know this is getting kinda annoying to me and you both ?? could we use ?? an array ?? somehow and would implemt every word into a array of it's own ?? it might sound good but i don't know how to do it thats another problem....

  8. #8
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Okay try this, I think it does what you want it to do (except for the menu)...

    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    class WordCount {
        private:
            ifstream infile;
            vector< string > words;
        public:
            void readWords( string );
            void writeWords();
            int getCount();
    };
    
    void WordCount::readWords( string fileName ) {
        infile.open( fileName.c_str() );
        if (!infile) {
            cerr << "Can't open file!\n";
            exit( 1 );
        }
    
        string s;
        while (infile >> s) {
            words.push_back( s );
        }
        infile.close();
    }
    
    void WordCount::writeWords() {
        vector< string >::const_iterator is;
        for (is = words.begin(); is < words.end(); is++) {
            cout << *is << endl;
        }
    }
    
    int WordCount::getCount() {
        return words.size();
    }
    
    
    int main() {
        WordCount w;
        w.readWords( "test.txt" );
        cout << w.getCount() << endl;
        w.writeWords();
    }
    Last edited by geophyzzer; 09-10-2002 at 06:57 PM.
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  9. #9
    Registered User
    Join Date
    Sep 2002
    Posts
    15
    didn't do nothing i got 14 errors in borland

  10. #10
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Must be your compiler options or something cause I got no errors from Borland after copy/pasting directly from the message in my web browser. Are you compiling as a console application? My compilation command was

    bcc32 -WC wordcount.cpp
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

  11. #11
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Compiled OK for me too (borland 5.5).

    Post some errors, Achillles.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  12. #12
    Registered User
    Join Date
    Sep 2002
    Posts
    15
    Cpp1.cpp(28) : error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (

    Cpp1.cpp(28) : fatal error C1903: unable to recover from previous error(s); stopping compilation

  13. #13
    Registered User
    Join Date
    Jun 2002
    Posts
    82
    Hmm...that looks totally bizarre...it looks like it doesn't know what to do with stream input into a string. Hate to ask a stupid question, but you are #including <iostream>, right? I have never seen anything like this. Any ideas, anybody?
    Claus Hetzer
    Compiler: Borland 5.5 (on Windows)
    Solaris CC (on Unix)
    Known Languages: C++, MATLAB, Perl, Java

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bintree and count (withouth using template)?
    By cubimongoloid in forum C++ Programming
    Replies: 7
    Last Post: 05-24-2009, 06:22 AM
  2. word count help?
    By n3cr0_l0rd in forum C Programming
    Replies: 13
    Last Post: 02-07-2009, 08:29 AM
  3. word count troubles
    By Hoser83 in forum C Programming
    Replies: 13
    Last Post: 02-09-2006, 09:12 AM
  4. Using 'if' with char arrays or string objects
    By c++_n00b in forum C++ Programming
    Replies: 36
    Last Post: 06-06-2002, 09:04 PM