Question: Suppose I give input to a C++ program as follows:

`1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`

C++ code:

```
int n;
for (int i = 0; i < 15; i++)
{
    std::cin >> n;
    // use the value of n to make changes
}

```

In the above code I can read the input sequentially,
 i.e. `1 2 3 4 5 6 7 8 9 10 11 12 13 14 15`.

Is there any way to read input directly (without using extra memory in C++ program) from the input stream in the following order:

`5 4 3 2 1 10 9 8 7 6 15 14 13 12 11`

First five digits in reverse order `5 4 3 2 1`, next five digits in reverse order `10 9 8 7 6`, ...

Answer: 
*No*.

You need to read the data as they flow into the input stream.

In your program then, you can re-order them in any way you like.
You need to wrap your taking input in some functionality that reorders the values for you. You might be able to do so outside the program, i.e., pipe the input stream through another program that reorders the values. Then your code might already work as you have it now.

Or you do this wrapping in your program. For example using a custom stream-like class that buffers the values in between.

There's no way to get this done without using extra memory to buffer the values you don't yet need.

Example:

```
#include <iostream>
#include <stack>

struct reader {
    std::stack<int> data;
    reader& operator>>(int & i) {
        if (data.empty()) {
            while (data.size() < 5) {
                data.push(0);
                std::cin >> data.top();
            }
        }
        i = data.top();
        data.pop();
        return *this;
    }
    explicit operator bool() const { return bool(std::cin); }
};

int main () {
    reader r;
    int i;
    while (r >> i) {
        std::cout << i << std::endl;
    }
}

```

Example output:

```
$ g++ tt.cc -std=c++11 && echo "1 2 3 4 5 6 7 8 9 10" | ./a.out
5
4
3
2
1
10
9
8
7
6

```

---

A more straight forward approach would probably be something like this:

```
#include <iostream>
#include <vector>

int main () {
    std::vector<int> buffer;
    for (int i; std::cin >> i; ) {
        buffer.push_back(i);
        if (buffer.size() == 5) {
            // do something with buffer
            //std::vector<int> reversed(buffer.rbegin(), buffer.rend());
            while (!buffer.empty()) {
                std::cout << buffer.back() << "\n";
                buffer.pop_back();
            }
        }
    }
}

```