Reading a file AND reversing it.

I have a file called numbers.dat, which all it has is a bunch of numbers.

The code below does read and display it in order, but what I need to do is to show it in reverse order.

So for example, the numbers are:

10
9
-2346
123
45096
2348
-10238192
1231270
29834230
847584
10
28
565
28
79
47
5969
85347
345
7593
7850
23945
95
26

And I need them displayed in the REVERSE order, so 26 would be first followed by 95, etc.

Below is the code that I have that reads them in order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {

ifstream file("numbers.dat");
string content;

while(file >> content) {
cout << content << ' ';
}
return 0;
}
Last edited on
You should store the numbers in a std::vector and then just print the vector contents in reverse.
Last edited on
I don't really know much about vectors. I know I need to have a #include<vector> at the top, but that's about it.

Do you have a sample of what you mean?

You don't mean like this?

1
2
3
4
5
6
7
8
vector<int> myArray(24); //24 is the amount of numbers in the file that I'm trying to read.

myArray[0] = 10;
myArray[1] = 9;
myArray[2] = -2346; /*These are the numbers, and for the sake of time I just wrote out the
                                 first 3 numbers. */

std::reverse(myArray.begin(), myArray.end());


You want to actually read the file into the vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
std::vector<int> numbers;
if(std::ifstream in {"numbers.dat"})
{
    int x;
    while(in >> x)
    {
        numbers.push_back(x);
    }
}
else
{
    //failed to open file
}
Later, just print out the vector contents in reverse.
Topic archived. No new replies allowed.