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?
Main function
Is this too long? is there a better way to do it?
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;
}
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;
}
Comment