working with text files

How could this be modified to also output the first and last word in the file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    using namespace std;
    //change FNAME here ... //
    const string FNAME = "test.txt";
    
    const string PUNC = ".?!,;";
    int main()
    {
    ifstream fin( FNAME.c_str() );
    if( fin )
    {
    int numWords = 0, numChars = 0;
    string word;
    cout << fixed << setprecision(0); // show NO decimal
    // input each word until end of file ... //
    while( fin >> word )
    {
    ++numWords;
    int len = word.size();
    // if last char is in string PUNC ... //
    if( PUNC.find( word[len-1] ) != string::npos )
    word.erase( len-1 );
    numChars += word.size();
    // show words ...//
    cout << ' ' << left << setw( 15 ) << word;
    }
    fin.close();
    cout << "\n\nNumber of words was " << numWords
    << "\nNumber of letters was " << numChars
    << "\nAverage letters per word was "
    << double(numChars) / numWords << endl;
    }
    else
    cout << "\nThere was a problem opening file "
    << FNAME << endl;
    cout << "\nPress 'Enter' to continue/exit ... ";
    cin.get();
    }
word is going to be the last word in the file at the very end. You could also read it into a variable called "first" or something for the very first word.
ok got the last word part, but how do i handle the first word?
also how could i find the longest word
Topic archived. No new replies allowed.