Challenge: Longest Word

Lab C++ Intermediate 20 points

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
Sample input available Sample output available
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
HOME LABS COMMUNITY DASHBOARD