Allball103
Allball103

Reputation: 131

How to print to file using ostream_iterator?

I have the following code (mooched from here) to randomize a vector of 1500 values, and I want to place them in a textfile but can't. Honestly, I don't fully understand how this code works, so I'd like someone to explain to me how it works and/or how to change the output to a file.

#include <iostream>
#include <random>
#include <algorithm>
#include <iterator>
#include <fstream>

int main() {
    std::vector<int> v;
    for (int i; i<1500; ++i){
        v.push_back(i);
    }

    std::random_device rd;
    std::mt19937 g(rd());

    std::shuffle(v.begin(), v.end(), g);

    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

    return 0;
}

Upvotes: 1

Views: 2162

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69912

The type of std::cout and the type std::ofstream are both derived from std::ostream, which is the same type that std::ostream_iterator operates on:

#include <iostream>
#include <random>
#include <algorithm>
#include <iterator>
#include <fstream>

void emit_values(std::ostream& os)
{
    std::vector<int> v;
    for (int i = 0; i<1500; ++i){
        v.push_back(i);
    }

    std::random_device rd;
    std::mt19937 g(rd());

    std::shuffle(v.begin(), v.end(), g);

    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(os, " "));
    os << "\n";
}

int main() 
{
    // use stdout
    emit_values(std::cout);

    // use a file
    std::ofstream fs("values.txt");
    emit_values(fs);
    fs.close();    

    return 0;
}

Upvotes: 2

Related Questions