Output Data from Input.txt to Output.txt

Say I have input.txt, which looks like this:
1
2
3
4
5
8
7
6
5
4


and output.txt, which looks like this:
1
2
3
4
5
6
6
5
4
3
2
1


I want to get it looking like this:
1
2
3
4
5
6
7
8
8
7
6
5
4
3
2
1


However, I am having great difficulty doing this. I can't seem to find a way to do it because when I output, it seems to write-over the previous output.txt. The only way I can think of doing this is making getline start from the bottom and work backwards up the txt file (instead of the usually working from top down).

Just checking if there is an easier way to achieve this goal, thanks!
Read both input and output file, then save everything to output.
Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <set>


int main()
{
    std::set<int, std::greater<int>> numbers;
    std::ifstream inp("input.txt");
    std::copy(std::istream_iterator<int>(inp), std::istream_iterator<int>(),
              std::inserter(numbers, numbers.end()));
    inp.close();
    inp.open("output.txt");
    std::copy(std::istream_iterator<int>(inp), std::istream_iterator<int>(),
              std::inserter(numbers, numbers.end()));
    inp.close();
    std::ofstream out("output.txt");
    std::copy(numbers.begin(), numbers.end(),
              std::ostream_iterator<int>(out, "\n"));
}
Last edited on
Your code compiled and ran great inside Visual but when I run with Dev C++, output.txt is left as a copy of input.txt and thus some of the data originally inside output.txt is lost.

Do you happen to know why that is?

I tried to do this with a .txt full of strings instead but couldn't seem to get it to compile. Does set work with strings?

Thanks for all your help, much appreciated!!! :)
Does set work with strings?
Yes, but you should change every int to std::string in code. Also strings in question are whitespace character (\n, \t, ' ') separated, so "Hello world" would be read as two strings.

Do you happen to know why that is?
What version of DevC++ do you use?
Topic archived. No new replies allowed.