C++: Words in a line

Report on the words in a line.

What to build

A program that splits text and answers three questions about it.

Requirements

  • Read a whole line.
  • Print words N.
  • Print longest W, using the earliest one if several are equally long.
  • Print the words in reverse order, separated by single spaces.

Input

One line with at least one word.

Output

Three lines.

Constraints

The line has at most 500 characters.

Example

Input:

the quick brown fox

Output:

words 4
longest quick
fox brown quick the

Why it works

Once the words are in a vector, each question becomes simple. Replacing the longest word only when a new one is strictly longer keeps the earliest of any tie.

Examples

Example 1 · Input
the quick brown fox
Expected output
words 4
longest quick
fox brown quick the
Example 2 · Input
hello
Expected output
words 1
longest hello
hello

Hints

Hint 1

Keep the words in a vector<string>, using istringstream.

Hint 2

Track the longest word as you read.

Hint 3

Loop backwards to print them in reverse.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string line, word;
    getline(cin, line);
    istringstream in(line);
    vector<string> words;
    string longest;
    while (in >> word) {
        words.push_back(word);
        if (word.size() > longest.size()) {
            longest = word;
        }
    }
    cout << "words " << words.size() << endl;
    cout << "longest " << longest << endl;
    for (int i = static_cast<int>(words.size()) - 1; i >= 0; i--) {
        cout << words[i];
        cout << (i > 0 ? " " : "\n");
    }
    return 0;
}

Lesson: The string class →