How to print an entire istream to standard out and string

后端 未结 5 687
既然无缘
既然无缘 2021-01-03 22:39

How do you print an istream variable to standard out. [EDIT] I am trying to debug a scenario wherein I need to ouput an istream to a log file

5条回答
  •  迷失自我
    2021-01-03 23:39

    Edit: I'm assuming that you want to copy the entire contents of the stream, and not just a single value. If you only want to read a single word, check 1800's answer instead.


    The obvious solution is a while-loop copying a word at a time, but you can do it simpler, as a nice oneliner:

    #include 
    #include 
    
    ...
    
    std::istream i;
    std::copy(std::istream_iterator(i), std::istream_iterator(), std::ostream_iterator(std::cout));
    

    The stream_iterators use operator << and >> internally, meaning they'll ignore whitespace. If you want an exact copy, you can use std::istreambuf_iterator and std::ostreambuf_iterator instead. They work on the underlying (unformatted) stream buffers so they won't skip whitespace or convert newlines or anything.

    You may also use:

     i >> std::noskipws;
    

    to prevent whitespace from disappearing. Note however, that if your stream is a binary file, some other characters may be clobbered by the >> and << operators.

提交回复
热议问题