0

I wrote a C++ program to take input values from a file, sort it and store it in another file. Here's my code.

#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    ifstream fin;
ofstream fout;

fin.open("input.txt", ios::in);
fout.open("output.txt",ios::out);

std::vector<int> v;
int i;
while(!fin.eof()){
    fin >> i;
    v.push_back(i); 
}

sort(v.begin(),v.end());
vector<int>::iterator it;
for( it = v.begin(); it != v.end(); it++){
    fout << *it << endl;
    cout << *it << endl;
    }
}

My input file let us say has this input.txt

3
4
7
1
5

The output file prints the last value twice. I have not been able to figue out why.

output.txt

1
3
4
5
5
7
sudha
  • 63
  • 1
  • 7
  • Read this: [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Then change `while (!fin.eof())` to `while (fin >> i)` and remove the `fin >> i` inside the loop body. – WhozCraig Jul 18 '17 at 17:01
  • @WhozCraig Thank you! – sudha Jul 18 '17 at 17:03

0 Answers0