Challenge: Longest Word
Completed
Read a whole line of words separated by spaces. Print the number of words, and then the longest word (if there is a tie, the first one).
Input
One line with at least one word.
Output
Words: 4 Longest: quick
Example
Input
the quick red fox
Output
Words: 4 Longest: quick
Editor
C++
Hints
getline the line, then put it into a stringstream.
while (ss >> word) gives you one word at a time.
Only replace the longest word when the new one is strictly longer (>).
Solution explanation
A stringstream splits the line for you; using > (not >=) keeps the first of equal-length words.
Show solution
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin, line);
stringstream ss(line);
string word, longest;
int count = 0;
while (ss >> word) {
count++;
if (word.length() > longest.length()) {
longest = word;
}
}
cout << "Words: " << count << "\n";
cout << "Longest: " << longest << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module