find longest word in file

how can i find and print the longest word?

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
42
43
    #include <iostream>
    #include <iomanip>
    #include <fstream>
    #include <string>
    using namespace std;

    const string FNAME = "test.txt";
   
    const string PUNC = ".?!,;";
    int main()
    {
    cout << "\n";
    cout << " FILENAME: " << FNAME << endl;
    cout << "\n";
    ifstream fin( FNAME.c_str() );
    if( fin )
    {
    int numWords = 0, numChars = 0;
    string word;
    cout << fixed << setprecision(0);
    while( fin >> word )
    {
    ++numWords;
    int len = word.size();
    if( PUNC.find( word[len-1] ) != string::npos )
    word.erase( len-1 );
    numChars += word.size();
    cout << ' ' << left << word;
    }
    fin.close();
    cout << "\n\n Number of words was " << numWords
    << "\n Number of letters was " << numChars
    << "\n Average letters per word was "
    << double(numChars) / numWords << endl;
    cout << " Last word in file is: " << word << " and it is " 
    << word.size() << " letters long\n";
    }
    else
    cout << "\nThere was a problem opening file "
    << FNAME << endl;
    cout << "\nPress 'Enter' to continue/exit ... ";
    cin.get();
    }
Last edited on
just create string x before while loop.
And in the loop if you find the word that word.size() > x.size(), do x = word.
Last edited on

Just to show you how it can be achieved (without the file stuff):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main()
{

	std::string Names[5] = { "Paula", "John", "Mark", "Jim", "Michael" };
	std::string Result;  // holds name

	for (int i = 0; i < 5; i++) {
		if (Names[i].length() > Result.length())
			Result = Names[i];
	}

	return 0;
}
Topic archived. No new replies allowed.