Start New Discussion within our Software Development Community

I can not get the program to read the entire sentence. The main is part of the assignment. Any suggestions would be a great help!

#include<iostream>
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] != ' ')
       {
           counter++;
       }
       else if(ptr[i] == ' ')
       {
            if(counter > longest_word)
       {
            longest_word = counter;
       }
            counter = 0;
     }
      
    }
     	 
	return longest_word;
    
}

The only obvious thing I see is that it doesn't try to save the length of the last word, it would appear to work for everything else.

The last word in the sentence won't be followed by a space, it will be followed by the end of the string.

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

If this wasn't your problem, be more specific: "When I input ___ I expected ___, but I'm seeing ___" type of description for the problem. Clear and concise, making it easy for us to help you works best.

This article has been dead for over six months. Start a new discussion instead.