/*This is an assignment for school. The main is part of the assignment. The program will work sometimes, sometimes it will not count the longest word if it is at the end of a sentence.*/

using std::cout;
using std::cin;

// Prototype for the longest_word function that you need to write. 
// Add consts where necessary to obey the principle of least privilege
int longest_word( char * ptr );

int main()
    const int MAX_LENGTH = 101; // only 100 non-null characters can fit in our array
    char phrase[MAX_LENGTH] = ""; // filling up the array with a bunch of null characters

    cout << "Enter a sentence or phrase\n";
    cin.getline( phrase, MAX_LENGTH ); // ensures that the input doesn't overstep the array bounds

    cout << "The longest word in your phrase is " << longest_word( phrase ) << " characters in length\n";

    return 0;

// implement the longest_word function here - the function should only count alphabetic characters in each word

int longest_word( char * ptr )

    int x;
    int counter = 0;
    int longest_word = -1;

    int length = int(strlen(ptr));

    for(int i=0; i<length; i++)
       if(ptr[i] != ' ')
       else if(ptr[i] == ' ')
            if(counter > longest_word)
            longest_word = counter;
            counter = 0;


    return longest_word;


Wow, deja vu, but better problem description.

The last word won't be followed by a space...

add another if (counter > longest_word) outside the for loop to handle the last word.

or alternatively...you could just add a space to the end of the string to make sure that there is one.

This question has already been answered. Start a new discussion instead.