logo
down
shadow

How to print to file using ostream_iterator?


How to print to file using ostream_iterator?

By : Roberto Oliveira
Date : October 16 2020, 03:08 PM
seems to work fine 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:
code :
#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;
}


Share : facebook icon twitter icon
Writing into binary file with the std::ostream_iterator

Writing into binary file with the std::ostream_iterator


By : user3878959
Date : March 29 2020, 07:55 AM
hope this fix your issue The std::stream_iterator uses the "normal" operator<< semantics, it is a formatted output (not binary).
From cppreference;
code :
#include <iostream>
#include <algorithm>
#include <utility>
#include <iterator>

using namespace std;

template <class T, class CharT = char, class Traits = std::char_traits<CharT>>
class ostreambin_iterator :
    public std::iterator<std::output_iterator_tag, void, void, void, void> {
public:
    typedef std::basic_ostream<CharT, Traits> ostream_type;
    typedef Traits traits_type;
    typedef CharT  char_type;

    ostreambin_iterator(ostream_type& stream) : stream_(stream) { }

    ostreambin_iterator& operator=(T const& value) 
    {
        // basic implementation for demonstration
        stream_.write(reinterpret_cast<const char*>(&value), sizeof(T));
        return *this;
    }

    ostreambin_iterator& operator*()     { return *this; }
    ostreambin_iterator& operator++()    { return *this; }
    ostreambin_iterator& operator++(int) { return *this; }

protected:
    ostream_type& stream_;
};

int main() {
    std::vector<long> d(3);
    d[0] = 0x303030; // test some width past a single byte
    d[1] = 0x31;
    d[2] = 0x32;

    ostreambin_iterator<long> out(cout);

    cout << "begin" << endl;
    copy(std::begin(d), std::end(d), out);
    cout << endl;
    cout << "end" << endl;
}
Using ostream_iterator to copy a map into file

Using ostream_iterator to copy a map into file


By : Guillem Torres Marqu
Date : March 29 2020, 07:55 AM
will be helpful for those in need If you look carefully at the declaration of std::ostream_iterator here, you will notice that your usage of std::ostream_iterator is incorrect because you should specify the type of printed elements as the first template parameter.
The type of elements in the std::map M is std::pair< const std::string, int >. But you can't put std::pair< const std::string, int > as the first template parameter because there is no default way to print an std::pair.
code :
std::ofstream out("file.txt");

std::for_each(std::begin(M), std::end(M),
    [&out](const std::pair<const std::string, int>& element) {
        out << element.first << " " << element.second << std::endl;
    }
);
Simple file writing with ostream_iterator creates file, but doesn't write

Simple file writing with ostream_iterator creates file, but doesn't write


By : Robin Farjad
Date : March 29 2020, 07:55 AM
Any of those help You are not flushing the stream to disk before calling system().
You can explicitly flush() or close() the stream:
code :
int main() {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    os.close();

    system("PAUSE");
    return 0;
}
int main() {
    {
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++) {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    }

    system("PAUSE");
    return 0;
}
Std::copy and std::ostream_iterator to use overloading function to print values

Std::copy and std::ostream_iterator to use overloading function to print values


By : 虎林火车站酒店小姐
Date : March 29 2020, 07:55 AM
hop of those help? std::ostream_iterator::operator= takes its parameter as const&. Internally, this will use operator<< to output each value into the stream.
But the parameter is const, so it can't be passed into your operator< code :
friend ostream& operator<<(ostream&os,  const Employee& obj )
{
    return os << obj.name << " "<< obj.salary;
}
Performance of ostream_iterator for writing numeric data to a file?

Performance of ostream_iterator for writing numeric data to a file?


By : Deepak Namala
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , The quickest (but most horrible) way to dump a vector will be to write it in one operation with ostream::write:
Related Posts Related Posts :
  • reinterpret_cast to a variable-sized array
  • Reading from text file to structure
  • c++ variant No such file or directory
  • What is the deduced type of a constexpr?
  • Cannot cout string when boost's io service is running
  • Case-insensitive keywords with boost::spirit::lex
  • why can't i pass two different comparators to one template function?
  • why auto doesn't detect reference type of function
  • If edges are not inserted in the deque in sorted order of weights, does 0-1 BFS produce the right answer?
  • Statically linked application - size reduction
  • C++ If-else statement using strings and comparing strings
  • Why cannot I delete unique_ptr<char[]> with reset()?
  • How to declare IN, OPTIONAL parameter along with OUT, RETVAL parameter in IDL
  • Symbol does not show up on ArcGIS Map using Qt
  • gdb stl functions still show as inlined after disabling optimizations
  • Get time difference from specific day
  • Undefined reference when using callbacks with ARM mbed
  • Is unevaluated division by 0 undefined behavior?
  • struct pointer function points to other function of other struct
  • How to print element of the map inside the vector?
  • Size of parameter pack in template specialization
  • std::string cannot be printed in gdb when it's global variable, why?
  • SONARQUBE C++ community plugin 9.0 and lower unavailable
  • How to initialize a class type used as a function parameter
  • Access object field in a CALLBACK function (WINAPI - C++)
  • c++ regex get folder from a file path
  • cannot convert argument of incomplete type 'void *' to 'const bitData'
  • C++ get/set not getting value in switch case
  • Shared pointer [] operator and ++ operator
  • standard way to put static objects together
  • Delete Elements from Vector Inside Loop
  • c++: How to flip the binary values of each bit in int
  • Strange Parent ID
  • How to fail static assertion if a class doesn't have default visibility
  • error in sscanf while scanning char[] and int
  • C++ Interfacing queue or priority_queue as template parameter of a class
  • JUCE - Member Function Not Viable: 'this' Argument Has Type const
  • Saving a brute force result for future use?
  • which header file contains ThrowIfFailed() in DirectX 12
  • 2D array pass in a function without Define (M x N) globally
  • Converting string to TDateTime in C++Builder 2009
  • Excel C API: Is there an Excel v4.0 macro function to test if a sheet is hidden?
  • std::setw for the whole operator<< of user-defined type
  • How do I setup an ODBC connection to perform multiple querys(SQLExecDirect) in c++?
  • Vectorization of modulo multiplication
  • C++ 11 thread class member function in for loop gives segmentation fault
  • Mesh boolean operation with CGAL
  • Best way to fix type conversion warnings in c++
  • How do to have a template deduce its parameters
  • Passing auto as a parameter (for pointer to object)
  • C++: MFC Application on both Windows 10 x64 & Windows 7 x64
  • Read stdin with C++ and concatenate inside string
  • No longer unable to retrieve data from QIODevice after calling readAll(). Buffer flushed?
  • g++ command line macro define byte stream
  • Why won't my variadic macro accept no arguments correctly?
  • Clang adds noinline attribute to all functions when emitting LLVM IR
  • as rptr->num=30 is same as (*rptr).num=30 but*((*rptr).ptr).name does not work why?
  • How to use get() multiple times in c++ 11 future or how to get a vector values?
  • libstdc++ cannot find thread file on Mac
  • Check if macro is odd in c++
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com