C++: Reverse the words of every line

Read text until it runs out, and turn every line around word by word.

What to build

A program that prints each line of the input with its words in reverse order.

Requirements

  • Keep reading lines until the end of the input.
  • Treat any run of spaces as one gap between words.
  • Print the words of each line from last to first, separated by single spaces.
  • Print an empty line for an empty input line.

Input

Any number of lines of words.

Output

The same number of lines, each with its words reversed.

Constraints

At most 100 lines, each with up to 200 characters.

Example

Input:

the cat sat
hello
one two three four

Output:

sat cat the
hello
four three two one

Why it works

Storing a line's words in a vector lets you visit them backwards. Reading with getline in a loop handles any number of lines, and stops by itself when the input ends.

Examples

Example 1 · Input
the cat sat
hello
one two three four
Expected output
sat cat the
hello
four three two one
Example 2 · Input
a  b

x y
Expected output
b a

y x

Hints

Hint 1

`while (getline(cin, line))` reads one line at a time until the input ends.

Hint 2

Split a line into words by collecting letters into a `string` and storing it in a `vector<string>` at each space.

Hint 3

Print the words from the last to the first, with one space between them.

Solution

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

int main() {
    string line;
    while (getline(cin, line)) {
        vector<string> words;
        string word = "";
        for (size_t i = 0; i <= line.length(); i++) {
            if (i == line.length() || line[i] == ' ') {
                if (word != "") words.push_back(word);
                word = "";
            } else {
                word += line[i];
            }
        }
        for (int i = (int)words.size() - 1; i >= 0; i--) {
            cout << words[i];
            if (i > 0) cout << " ";
        }
        cout << endl;
    }
    return 0;
}

Lesson: From C to C++ →