String Practice Problems Problem 2: Write a full program (starting from #include
ID: 3726606 • Letter: S
Question
String Practice Problems
Problem 2:
Write a full program (starting from #include) that asks the user to type in 10 words, prompting the user for each word with a number. The program then reports the longest word the user typed in. A sample output is shown below, with the user input shown in italic print.
Enter word #1: Gandalf
Enter word #2: hobbit
Enter word #3: Frodo
Enter word #4: orc
Enter word #5: antidisestablishmententarianism Enter word #6: Sauron
Enter word #7: ringEnter word #8: Sam
Enter word #9: Legolas
Enter word #10: Aragorn
The longest word is antidisestablishmententarianism.
To receive full credit, you must use a while loop. Do not write 10 cin statements.
Could you please be kind enough and answer in detail?
Thank you for ereading this and have a good one!
Explanation / Answer
SOLUTION:-
#include <iostream>
#include <string>
using namespace std;
int main()
{
string word, longest_word;
int longest_word_length = 0;
int NUMBER = 1;
while (NUMBER <= 10)
{
cout << "Enter word #" << NUMBER << ": ";
cin >> word;
if (word.length() > longest_word_length)
{
longest_word = word;
longest_word_length = word.length();
}
NUMBER++;
}
cout << "The longest word is " << longest_word << ". ";
return 0;
}
==================================================================================