无法成功生成文件和控制台的std::set输出

Can not successfully generate the std::set output to the file and console

本文关键字:std set 输出 控制台 成功 文件      更新时间:2023-10-16

我正在尝试从文件中读取一个整数列表,并将它们存储到std::set容器中,然后将整数输出到控制台,然后生成输出文件。我试过做那件事,但没能成功。如果我在程序中使用.erase(),那么我可以在控制台上看到输出和一个没有文本的空文件。如果我不使用.erase(),那么我有无限循环的运行时错误

#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");
}`
#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;
}

示例:http://ideone.com/1Cil1C

您没有正确使用iterator

set<int>::iterator iter = myset.begin();
ofstream out_data("Ahmad.txt");
for(; iter != myset.end(); iter++)
{
    cout << *iter << " ";
    out_data << *iter << " ";
}

在显示的循环中擦除它们

// 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 << " ";