1

I am trying to read a list of integers from a file and store them to std::set container, after that want to output the integers to the console and then generate the output file. I have tried to do it but could not succeed. If I use .erase() in my program then I can see the output on the console and an empty file without text. If I do not use the .erase() then I have run time error of infinite loop. `

#include <iostream>
#include <set>
#include <fstream>
#include <iterator>
using namespace std;

int main()
{

    set<int> myset;

    fstream textfile;
    textfile.open("input.txt");  // opening the file 

    // reading input from file 
    while (!textfile.eof())
    {
        int iTmp = 0;
        textfile >> iTmp;
        myset.insert(iTmp);


    }

    // output to the console
    set<int>::iterator iter = myset.begin();
    while (!myset.empty())
    {
        cout << *myset.begin() << " ";
        myset.erase(myset.begin());
    }

    // writting output to the file

    ofstream out_data("Ahmad.txt");

    while (!myset.empty())
    {
        out_data << *myset.begin() << " ";
    }



    system("pause");
}`
チーズパン
  • 2,672
  • 8
  • 38
  • 58
James
  • 59
  • 8
  • Unrelated to your problem, but you might want to read ["Why is iostream::eof inside a loop condition considered wrong?"](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Some programmer dude Apr 19 '16 at 09:14

3 Answers3

2
#include <iostream>
#include <iterator>
#include <set>
using namespace std;

int main() {
    using data_type = int;
    set<data_type> data_set;

    //change cin to your ifstream
    copy(istream_iterator<data_type>(cin), 
         istream_iterator<data_type>(), 
         inserter(data_set, end(data_set)));

    //change cout to your ofstream
    copy(begin(data_set), end(data_set), ostream_iterator<data_type>(cout, " "));

    return 0;
}

example: http://ideone.com/1Cil1C

Patryk Wertka
  • 169
  • 1
  • 5
1

You are not using the iterator properly.

set<int>::iterator iter = myset.begin();
ofstream out_data("Ahmad.txt");

for(; iter != myset.end(); iter++)
{
    cout << *iter << " ";
    out_data << *iter << " ";
}
Nadir
  • 1,674
  • 10
  • 19
0

you are erasing them in the loop where you display them

// output to the console
for (auto& x : myset)
    cout << x << " ";

// writting output to the file
ofstream out_data("Ahmad.txt");
for (auto& x : myset)
    out_data << x << " ";
Exceptyon
  • 1,570
  • 17
  • 22