473,765 Members | 1,869 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

word count problem

3 New Member
can anyone debug my program and get it to run.

Expand|Select|Wrap|Line Numbers
  1. #include <fstream>  
  2. #include <iostream> 
  3. #include <string>   
  4. #include <cstdlib>
  5. #include <map> 
  6.  
  7. using namespace std; 
  8.  
  9.  
  10.  
  11. string getInputFileName(); // a function to prompt for the complete file name
  12.  
  13. int numCharsInFile( ifstream &in, int &numLines ); // a function to count the
  14.                                                    //    number of characters and
  15.                                                    //    lines in a text file
  16.  
  17. int numWordsInFile( ifstream &in, int &numWords ); // a function to count words in file
  18.  
  19. string get_tokenInFile( ifstream &in, int &numWords ); // a function to count frequency of words in file
  20.  
  21.  
  22.  
  23.  main ()
  24. {
  25.  
  26.  
  27.     char c;
  28.   int nLines,          // number of lines in the text file
  29.       nChars,          // number of characters in the text file
  30.       avgCharsPerLine, // average number of characters per line
  31.       nWords;
  32.   string nWords1;          // number of words in the text file
  33.  
  34.  
  35.  
  36.   ifstream inFile; // handle for the input text file
  37.  
  38.   string fileName; // complete file name including the path
  39.  
  40.   fileName = getInputFileName(); // prompt and obtain the full file name
  41.  
  42.   inFile.open(fileName.c_str()); // try to open the file
  43.  
  44.   if( !inFile.is_open() )    // test for unsuccessfull file opening
  45.    {
  46.      cerr << "Cannot open file: " << fileName << endl << endl;
  47.      exit (0);
  48.    }
  49.  
  50.  
  51.   nChars = numCharsInFile( inFile, nLines ); // determine the number of lines
  52.                                             //    and characters in the file
  53.   nWords = numWordsInFile( inFile, nWords ); // determine the number of words
  54.  
  55.   nWords1 = get_tokenInFile( inFile, nWords1 ); // determine the frequency of characters
  56.  
  57.   avgCharsPerLine = nChars / nLines;
  58.  
  59.  
  60.  
  61.  
  62.   cout << "The number of characters in the file: " << fileName
  63.        << " is = " << nChars << endl << endl;
  64.  
  65.   cout << "The number of lines in the file: " << fileName
  66.        << " is = " << nLines << endl << endl;
  67.  
  68.  
  69.   cout << "The number of Words in the file: " << fileName
  70.        << " is = " << nWords << endl << endl;
  71.  
  72.   cout << "The average number of characters per line in the text file: "
  73.        << fileName << " is: " << avgCharsPerLine << endl << endl;
  74.  
  75.   cout << "The frequency of Words in the file: " << fileName
  76.        << " is = " << nWords1 << endl << endl;
  77.  
  78.     cin>>c;
  79.   inFile.close(); // close the input file
  80.  
  81. }
  82.  
  83.  
  84.  
  85. string getInputFileName()
  86.  {
  87.    string fName; // fully qualified name of the file
  88.  
  89.    cout << "Please enter the fully qualified name of the " << endl
  90.         << "input text file (i.e. including the path): ";
  91.    cin >> fName; // cannot handle blanks in a file name or path
  92.    cout << endl; 
  93.  
  94.    return fName;
  95.  }
  96.  
  97.  
  98.  
  99.  
  100.  
  101. int numCharsInFile( ifstream &in, int &numLines )
  102.  {
  103.    int numChars = 0; 
  104.  
  105.    char ch; // character holder;
  106.  
  107.    numLines = 0; // initialize the number of lines to zero
  108.  
  109.    while ( in.get(ch) ) // get the next character from the file
  110.                         //   the function get will also get whitespace
  111.                         //   i.e. blanks, tabs and end of line characters
  112.  
  113.     {
  114.      if (ch != ' ' )
  115.      {
  116.        if(ch != '\n')
  117.        numChars++;// increase the count of characters by one if ch is NOT '\n' AND NOT a blank space
  118.        else
  119.        {
  120.        numLines++;     // increase the count of lines by one if ch IS '\n'
  121.        }
  122.      } 
  123.     }
  124.     numLines += 1; // for some reason it needs to add one and the results are correct
  125.    return numChars; // return the number of characters in the file
  126.  }
  127.  
  128.  
  129.  
  130.  
  131. int numWordsInFile( ifstream &in, int &nWords)
  132.  {
  133.     in.clear();
  134.  
  135.     in.seekg(0, ios_base::beg); // IS THIS CORRECT UBERGEEK?
  136.  
  137.     int numWords = 0 ; 
  138.  
  139.    char ch; 
  140.  
  141.  
  142.    while (in.get(ch)) 
  143.    {      
  144.  
  145.     if ( ch == ' ' || ch == '\n' || ch == '\t' ) 
  146.        numWords++;    
  147.  
  148.  
  149.     }
  150.  
  151.    return numWords+1; // for some reason again it needs to add one to work properly
  152.  }  
  153.  
  154.   string get_token( ifstream &in, string nWords1)
  155. {
  156.     string token;
  157.  
  158.     char ch;
  159.  
  160.     while (in.get(ch))
  161.     {
  162.         char c;
  163.         in.get(ch)>> c;
  164.         if ( isalpha( c ) || c == '\'' )
  165.             token += c;
  166.         else if ( token.size() )
  167.         return token;
  168.  
  169.  
  170.  
  171.     }
  172.     return token;
  173. }
  174. string token = get_token( infile );
  175.     if ( token.size() == 0 )
  176.         break;
  177.     map<string, int>::const_iterator ii = frequency.find( token );
  178.     if ( ii == frequency.end() )
  179.         frequency[ token ] = 1;
  180.     else
  181.         frequency[ token ]++;
  182.  
  183.     multimap<int, string> counts;
  184.     for ( map<string, int>::iterator ii = frequency.begin() ; 
  185.           ii != frequency.end();
  186.           ii++ )
  187.       counts.insert( pair<int,string>( (*ii).second, (*ii).first ) )
  188.  
  189. set<string> used_codes;
  190. for ( multimap<int, string>::reverse_iterator jj = counts.rbegin() ; 
  191.       jj != counts.rend() ; 
  192.       jj++ )
  193. {
  194.   string code = create_star_code( (*jj).second, used_codes );
  195.   used_codes.insert( code );
  196.   codes[ (*jj).second ] = code;
  197.   cout <<(*jj).second <<" " <<code <<" " <<(*jj).first <<endl;
  198. }
Nov 7 '07 #1
3 7793
scruggsy
147 New Member
Help us help you.
Put your code in [ code ] tags and describe what problem you are having with this program.
Nov 7 '07 #2
waynejr25
3 New Member
Help us help you.
Put your code in [ code ] tags and describe what problem you are having with this program.
The code works but my last function to count the frequency of each word in a txt file is not working can you please help me i need this program to graduate.
Nov 8 '07 #3
scruggsy
147 New Member
Seriously:

Help us help you.
Put your code in [ code ] tags and describe what problem you are having with this
program.
What, specifically, is happening when you try to run and/or compile this program? Compiler errors? Incorrect results?

Look at your code in the [ code] [/code ] tags below (much easier to read that way, isn't it?)
Expand|Select|Wrap|Line Numbers
  1. #include <fstream>  
  2. #include <iostream> 
  3. #include <string>   
  4. #include <cstdlib>
  5. #include <map> 
  6.  
  7. using namespace std; 
  8.  
  9.  
  10.  
  11. string getInputFileName(); // a function to prompt for the complete file name
  12.  
  13. int numCharsInFile( ifstream &in, int &numLines ); // a function to count the
  14.                                                    //    number of characters and
  15.                                                    //    lines in a text file
  16.  
  17. int numWordsInFile( ifstream &in, int &numWords ); // a function to count words in file
  18.  
  19. string get_tokenInFile( ifstream &in, int &numWords ); // a function to count frequency of words in file but this function isn't working
  20.  
  21.  
  22.  
  23.  main ()
  24. {
  25.  
  26.  
  27.     char c;
  28.   int nLines,          // number of lines in the text file
  29.       nChars,          // number of characters in the text file
  30.       avgCharsPerLine, // average number of characters per line
  31.       nWords;
  32.   string nWords1;          // number of words in the text file
  33.  
  34.  
  35.  
  36.   ifstream inFile; // handle for the input text file
  37.  
  38.   string fileName; // complete file name including the path
  39.  
  40.   fileName = getInputFileName(); // prompt and obtain the full file name
  41.  
  42.   inFile.open(fileName.c_str()); // try to open the file
  43.  
  44.   if( !inFile.is_open() )    // test for unsuccessfull file opening
  45.    {
  46.      cerr << "Cannot open file: " << fileName << endl << endl;
  47.      exit (0);
  48.    }
  49.  
  50.  
  51.   nChars = numCharsInFile( inFile, nLines ); // determine the number of lines
  52.                                             //    and characters in the file
  53.   nWords = numWordsInFile( inFile, nWords ); // determine the number of words
  54.  
  55.   nWords1 = get_tokenInFile( inFile, nWords1 ); // determine the frequency of characters
  56.  
  57.   avgCharsPerLine = nChars / nLines;
  58.  
  59.  
  60.  
  61.  
  62.   cout << "The number of characters in the file: " << fileName
  63.        << " is = " << nChars << endl << endl;
  64.  
  65.   cout << "The number of lines in the file: " << fileName
  66.        << " is = " << nLines << endl << endl;
  67.  
  68.  
  69.   cout << "The number of Words in the file: " << fileName
  70.        << " is = " << nWords << endl << endl;
  71.  
  72.   cout << "The average number of characters per line in the text file: "
  73.        << fileName << " is: " << avgCharsPerLine << endl << endl;
  74.  
  75.   cout << "The frequency of Words in the file: " << fileName
  76.        << " is = " << nWords1 << endl << endl;
  77.  
  78.     cin>>c;
  79.   inFile.close(); // close the input file
  80.  
  81. }
  82.  
  83.  
  84.  
  85. string getInputFileName()
  86.  {
  87.    string fName; // fully qualified name of the file
  88.  
  89.    cout << "Please enter the fully qualified name of the " << endl
  90.         << "input text file (i.e. including the path): ";
  91.    cin >> fName; // cannot handle blanks in a file name or path
  92.    cout << endl; 
  93.  
  94.    return fName;
  95.  }
  96.  
  97.  
  98.  
  99.  
  100.  
  101. int numCharsInFile( ifstream &in, int &numLines )
  102.  {
  103.    int numChars = 0; 
  104.  
  105.    char ch; // character holder;
  106.  
  107.    numLines = 0; // initialize the number of lines to zero
  108.  
  109.    while ( in.get(ch) ) // get the next character from the file
  110.                         //   the function get will also get whitespace
  111.                         //   i.e. blanks, tabs and end of line characters
  112.  
  113.     {
  114.      if (ch != ' ' )
  115.      {
  116.        if(ch != '\n')
  117.        numChars++;// increase the count of characters by one if ch is NOT '\n' AND NOT a blank space
  118.        else
  119.        {
  120.        numLines++;     // increase the count of lines by one if ch IS '\n'
  121.        }
  122.      } 
  123.     }
  124.     numLines += 1; // for some reason it needs to add one and the results are correct
  125.    return numChars; // return the number of characters in the file
  126.  }
  127.  
  128.  
  129.  
  130.  
  131. int numWordsInFile( ifstream &in, int &nWords)
  132.  {
  133.     in.clear();
  134.  
  135.     in.seekg(0, ios_base::beg); // IS THIS CORRECT UBERGEEK?
  136.  
  137.     int numWords = 0 ; 
  138.  
  139.    char ch; 
  140.  
  141.  
  142.    while (in.get(ch)) 
  143.    {      
  144.  
  145.     if ( ch == ' ' || ch == '\n' || ch == '\t' ) 
  146.        numWords++;    
  147.  
  148.  
  149.     }
  150.  
  151.    return numWords+1; // for some reason again it needs to add one to work properly
  152.  }  
  153.  
  154.   string get_token( ifstream &in, string nWords1) //this is where i'm having the problems
  155. {
  156.     string token;
  157.  
  158.     char ch;
  159.  
  160.     while (in.get(ch))
  161.     {
  162.         char c;
  163.         in.get(ch)>> c;
  164.         if ( isalpha( c ) || c == '\'' )
  165.             token += c;
  166.         else if ( token.size() )
  167.         return token;
  168.  
  169.  
  170.  
  171.     }
  172.     return token;
  173. }
  174. string token = get_token( infile );
  175.     if ( token.size() == 0 )
  176.         break;
  177.     map<string, int>::const_iterator ii = frequency.find( token );
  178.     if ( ii == frequency.end() )
  179.         frequency[ token ] = 1;
  180.     else
  181.         frequency[ token ]++;
  182.  
  183.     multimap<int, string> counts;
  184.     for ( map<string, int>::iterator ii = frequency.begin() ; 
  185.           ii != frequency.end();
  186.           ii++ )
  187.       counts.insert( pair<int,string>( (*ii).second, (*ii).first ) )
  188.  
  189. set<string> used_codes;
  190. for ( multimap<int, string>::reverse_iterator jj = counts.rbegin() ; 
  191.       jj != counts.rend() ; 
  192.       jj++ )
  193. {
  194.   string code = create_star_code( (*jj).second, used_codes );
  195.   used_codes.insert( code );
  196.   codes[ (*jj).second ] = code;
  197.   cout <<(*jj).second <<" " <<code <<" " <<(*jj).first <<endl;
  198. }
get_token() ends at the closing brace immediately following return token. All the code beyond that brace is outside of any function. Surely that's not what you want?
Nov 8 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

5
13573
by: The Roys | last post by:
Hi Im doing something wrong in quitting the Word.Application in my VB program. I have General Declarations Dim AppWord As Word.Application Form_Load() Set AppWord = CreateObject("Word.Application")
5
7652
by: jester.dev | last post by:
Hello, I'm learning Python from Python Bible, and having some problems with this code below. When I run it, I get nothing. It should open the file poem.txt (which exists in the current directory) and count number of times any given word appears in the text. #!/usr/bin/python
3
8818
by: agent mike | last post by:
I am trying to count words in a text file. I am using the following code: in_stream.get(c); if(c == ' ' || c == '.' || c == ',') word_count++; and the word count is too low. If I include " .... || c == '\n' the word count is too high as it counts returns of blank lines as a word.
5
12871
by: STeve | last post by:
Hey guys, I currently have a 100 page word document filled with various "articles". These articles are delimited by the Style of the text (IE. Heading 1 for the various titles) These articles will then be converted into HTML and saved. I want to write a parser through vb.net that uses the word object model and was wondering how this could be achieved? The problem i am running into is that i can not test whether the selected text is...
2
13532
by: Mikey | last post by:
Sample VB .NET source code to create mailing labels or customized letters using MS Word MailMerge This VB .NET source code will start MS Word and call methods and set properties in MS Word to execute a MailMerge to create mailing labels or customized letters. A label name known to MS Word MailMerge mailing label wizard may be used or a template file containing the field names Line1 thru Line5 for each record to be printed. If a...
1
7650
by: Adam Faulkner via DotNetMonster.com | last post by:
I had a problem before extracting pages from an existing word document and then inserting the content into a new word document. The following code below works with Microsoft Word 2000 Function ParseWordDoc(ByVal Filename As String) As String Dim sNewFileName As String Dim WordApp As Word.Application = New Word.Application Dim BaseDoc As Word.Document Dim DestDoc As Word.Document
1
4215
by: vmoreau | last post by:
I have a text and I need to find a Word that are not enclosed in paranthesis. Can it be done with a regex? Is someone could help me? I am not familar with regex... Example looking for WORD: (there is a WORD in ( my string WORD )) and * WORD * to (find WORD) and * WORD * Should give me the to word between star (star ar not part of string)
4
12441
by: etuncer | last post by:
Hello All, I have Access 2003, and am trying to build a database for my small company. I want to be able to create a word document based on the data entered through a form. the real question is this: can Access create the document and place it as an OLE object to the relevant table? Any help is greatly appreciated. Ricky
2
4964
by: beanie | last post by:
i am a beginer in c programming and i am trying to Create a Concordance of Word Count for a Text File but my code is not working.pls can anyone helpme out.here is my code: #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> struct word { struct word *left; /* tree to the left */ struct word *right; /* tree to the right */ char *WORD;
6
3391
by: boyindie86 | last post by:
Hi I have been fighting with this lump of code for the last week what I am trying to do is that I am passing words into passages of texts, and I want the system to go and find exact word matches only and place square brackets around them e.g word = car PASSAGE: the red car required a lot of care to prevent a scar I only want it to place a square bracket around the word car and ignore the car in "Care" and "scar"
0
9566
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9393
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9946
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9832
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8830
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7371
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5272
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3530
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2800
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.