Sorting help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rjddude1
    New Member
    • Aug 2009
    • 7

    Sorting help

    I need to only get the first line from the file (until it encounters first period [.]) and also sort the output in descending order. could you help me out here?
    Code:
    //function declaration
    void countLetters( string s )
    {
      int pos, sum = 0;
      char m;
      ofstream outfile;
      outfile.open( "output.txt" );
      outfile << "Letter" << "\t" << "Occurences" << endl;
      
      // only a to z
      for( m = 97; m < 123; m++ )
      {
        // start with index = 0
        pos = s.find( m, 0 );
        while( pos != string::npos )
        {
          // adjust index up
          pos = s.find( m, pos+1 );
          // total up this character
          sum++;
        } 
        if ( sum > 0)
        {
          outfile << m << "\t" << sum << endl;
    	  if ( outfile.fail() )
    	  {
    		cout << "Error opening output file" << endl;
    		exit(1);
          }
          cout << m << "\t" << sum << endl;
        }
        sum = 0;
      }
      outfile.close();
      return;
    }
    Main function
    Code:
    //Main function
    
    #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <string>
    #include "lettercount.h"
    using namespace std;
    int main()
    {
    
        char c = 0;
        string str1, infilename;
        ifstream infile;
        cout << "Enter file name: ";
        getline(cin, infilename);
        
        infile.open ( infilename.c_str() );
        
        if ( infile.fail() )
    	{
    		cout << "Failed to open the file." << endl;
    		system ("pause");
            return 0;
    	}
    	
       // loop while extraction from file is possible
       while ( infile.good() )
       {
           // get character from file
           c = infile.get();
           cout << c;
        // build string with all lower case characters
           c = tolower( c );
           str1.push_back( c );
        }
        
        cout << "\nConverted string to lower alphabets: " << endl;
        cout << str1 << endl;
        // count letters a to z
        cout << "Letters" << "\t" << "Occurences" << endl;
        countLetters(str1);
        
        infile.close();
        
    	system("pause");
    	return 0;
    }
    Is this too long? is there a better way to do it?
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    Lets look at what you are doing.

    First, you are suppose to read the first sentence from a file. You are reading the complete file, not just the first sentence. You should stop when you find a '.' in the file.

    Second, you want to sort, but you are counting the number of a's, b's, c's, etc. in the file, regardless of case.

    Is this what you want to do?

    Comment

    Working...