Results 1 to 3 of 3

Thread: C++ problems while reading a file

  1. #1

    Thread Starter
    Frenzied Member System_Error's Avatar
    Join Date
    Apr 2004
    Posts
    1,111

    C++ problems while reading a file

    Hey people, I have a problem. My assignment was to add on to the previously coded class that counts the numbers of words and digits so that it would count the number of numbers:

    Code:
    #include <fstream>
    #include <iostream>
    #include <iomanip>
    #include <cctype>
    
    using namespace std;
    
    enum Features {UPPER, LOWER, DIGIT, IGNORE, EOW, EOS, NUMBER};
    
    // Function prototypes
    void OpenFiles(ifstream&, ofstream&);
    void getNumberCount(int&, ifstream&);
    Features Decode(char character);
    void ProcessCharacter(char, int&, int&, int&, int&, int&, int&);
    void PrintTable(ofstream& table, int, int, int, int, int, int, int);
    
    int main()
    {
        // Prepare files for reading and writing
        ifstream text;
        ofstream table;
        OpenFiles(text, table);
        char character;                 // Input character	
      
        // Declare and initialize counters
        int uppercaseCounter = 0;
        int lowercaseCounter = 0;
        int digitCounter = 0;
        int wordCounter = 0;
        int sentenceCounter = 0;
        int ignoreCounter = 0;
        int numberCounter = 0;
        text.get(character);  
        do
        { // Process each character
            ProcessCharacter(character, uppercaseCounter, 
                lowercaseCounter, digitCounter, sentenceCounter,
                wordCounter, ignoreCounter);
            text.get(character);          // Input one character  
        } while (text);                                              
        getNumberCount(numberCounter, text);
        PrintTable(table, uppercaseCounter, lowercaseCounter,
            digitCounter, sentenceCounter, wordCounter, ignoreCounter, numberCounter);
      text.close();
      table.close();
      
      return 0;
    }
    
    //******************************************************************        
    
    Features Decode( /* in */ char character ) // Character decoded
    
    // Function Decode examines the character and returns its type
    // Postcondition:
    //     Return value is the enumerated type to which character
    //     belongs
    
    {
        if (isupper(character))
            return UPPER;  
        else if (islower(character))
            return LOWER;  
        else if (isdigit(character))
            return DIGIT;    
        else 
            switch  (character)
            {
                case '.'  :
                case '?'  :
                case '!'  :  return EOS;
                         
                case ' '  :
                case ','  :
                case ';'  :
                case ':'  :  
                case '\n' :  return EOW;
          
            }
        return IGNORE;  
    }
        
    //****************************************************************** 
    
    void OpenFiles( /* inout */ ifstream& text,   // Input file
                    /* inout */ ofstream& table ) // Output file
    
    // Function OpenFiles reads in the names of the input file and the 
    // output file and opens them for processing; input file name is
    // written on the output file
    // Postcondition:
    //     Files have been opened AND the input file name has been
    //     written on the output file
    
    {
        string inFileName;
        string outFileName;
        cout << "Enter the name of the file to be processed" << endl;
        cin >> inFileName; 
        text.open(inFileName.c_str());
        cout << "Enter the name of the output file" << endl;
        cin >> outFileName;
        table.open(outFileName.c_str());
        table << "Analysis of characters on input file " << inFileName 
              << endl << endl;
    }
    
    //******************************************************************        
    
    void PrintTable
        ( /* inout */ ofstream& table,      // Output file
          /* in */ int uppercaseCounter,    // Uppercase letters
          /* in */ int lowercaseCounter,    // Lowercase letters 
          /* in */ int digitCounter,        // Digits
          /* in */ int sentenceCounter,     // '.', '?', '!' 
          /* in */ int wordCounter,         // Words 
          /* in */ int ignoreCounter,       // Everything else
          /* in */ int numberCounter)      // Numbers
    
    // Function PrintTable prints the percentages represented by each
    // of the five categories
    // Postcondition:
    //     The output has been written on file table, appropriately
    //     labeled
    
    {
        int totalAlphaNum;
        totalAlphaNum = uppercaseCounter + lowercaseCounter 
            + digitCounter;
      
        // Print results on file table 
        table << "Total number of alphanumeric characters: " 
              << totalAlphaNum << endl;    
        table << "Number of uppercase letters: " << uppercaseCounter 
              << endl;
        table << "Number of lowercase letters: " << lowercaseCounter 
              << endl;
        table << "Number of digits: " << digitCounter << endl;  
        table << "Number of characters ignored: " << ignoreCounter 
              << endl;      
        table << "Number of Numbers: " << numberCounter << endl;                    
      
        // Add number of end-of-sentence markers to the word count  
        wordCounter = wordCounter + sentenceCounter;
        
        // Write rest of results on file table
        table << "Number of Words: " <<  wordCounter << endl;
        table << "Number of Sentences: " << sentenceCounter << endl;
        table << "Average word length: " << fixed << setprecision(2) 
              << float(totalAlphaNum)/ wordCounter  << endl;
        table << "Average sentence length: " << fixed << setprecision(2) 
              << float(wordCounter) / sentenceCounter << endl;
      
    }   
    
    //*****************************************************************        
    
    void ProcessCharacter
        ( /* in  */   char character,       // Character to be 
                                            // processed
          /* inout */ int& uppercaseCounter, // Uppercase letters
          /* inout */ int& lowercaseCounter, // Lowercase letters 
          /* inout */ int& digitCounter,     // Digits
          /* inout */ int& sentenceCounter,  // '.', '?', '!' 
          /* inout */ int& wordCounter,      // Words 
          /* inout */ int& ignoreCounter)    // Everything else
    
    // Function ProcessCharacter examines character and increments the
    // appropriate counter.
    // Postcondition:
    //     The category to which the character belongs has been 
    //     incremented
    
    {
        static bool endOfWord = false;
    
        switch (Decode(character))
        {
            case UPPER :  uppercaseCounter++;
                          endOfWord = false;
                          break;
            case LOWER :  lowercaseCounter++;
                          endOfWord = false;
                          break;
            case DIGIT :  digitCounter++;  
                          endOfWord = false;
                          break;
            case EOW   :  if (!endOfWord)
                          {
                              wordCounter++;
                              endOfWord = true;
                          }  
                          break;
            case EOS   :  sentenceCounter++;
            	          endOfWord = true;
                          break;
            case IGNORE:  ignoreCounter++;
                          break;            
        }   
    }
    
    void getNumberCount(int& numberCounter, ifstream& text)
    {
         string line;
         while ( getline(text,line) )
         {
            for (int i=0; i<line.length(); ++i)
            {
               if (isdigit(line[i]))
              {
                int x = line.find_first_of(' ', i);
                if (x < 1000)
                {
                  string sub = line.substr(i+1, x-i-1);
                  int lenCounter = 0;
                  for (int j=0; j<sub.length(); ++j)
                  {
                     bool dig = isdigit(sub[j]);
                     if ( dig == true || (sub[j] == '.') )
                     {
                        lenCounter++;
                     }
                     else
                     {
                     }
                  }
                  if (lenCounter == sub.length())
                  {
                    numberCounter++;
                  }
                  if (x < line.length())
                  {
                        i = x;
                  }
                  else
                  {
                      break;
                  }
                }
                else
                {
                  break;
                }
             }
          }
       }
    }
    The problem is here:

    Code:
    int main()
    {
        // Prepare files for reading and writing
        ifstream text;
        ofstream table;
        OpenFiles(text, table);
        char character;                 // Input character	
      
        // Declare and initialize counters
        int uppercaseCounter = 0;
        int lowercaseCounter = 0;
        int digitCounter = 0;
        int wordCounter = 0;
        int sentenceCounter = 0;
        int ignoreCounter = 0;
        int numberCounter = 0;
        text.get(character);  
        do
        { // Process each character
            ProcessCharacter(character, uppercaseCounter, 
                lowercaseCounter, digitCounter, sentenceCounter,
                wordCounter, ignoreCounter);
            text.get(character);          // Input one character  
        } while (text);                                              
        getNumberCount(numberCounter, text);
      
      return 0;
    }
    If I call the getNumberCount after the do while statement, then I don't get anything. If I call it before the do-while statement, I get the correct number of numbers, but then it goes crazy when it gets to the do-while and the results are really skewed. It actually shows the number of sentences and words is -1#j. Does anyone know why I'm having this problem? If you read from a file once, then can you not read correctly again?
    Last edited by System_Error; Jan 21st, 2006 at 07:28 PM.

  2. #2
    Lively Member
    Join Date
    Nov 2005
    Posts
    68

    Re: C++ problems while reading a file

    After do loop: text.seekg(0, ios_base::beg) (go to the begining of the file)
    "bla, bla,... exists number M so for each n > M bla, bla..." Exists? Where is it? (Kronecker said...)

  3. #3
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: C++ problems while reading a file

    But your solution is probably not what was intended by the instructions. I think they want you to adapt ProcessCharacter to keep track of words that consist entirely of digits, and count those.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width