tags:

views:

1481

answers:

4

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

+1  A: 

This will print the whole stream, 1 character at a time:

char c;
c = my_istream.get();
while (my_istream)
{
    std::cout << c;
    c = my_istream.get();
}

This will print the whole thing, but discard whitespace:

std::string output;
while(my_istream >> output)
    std::cout << output;
rlbond
+6  A: 

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:

std::istream i;
std::copy(std::istream_iterator<char>(i), std::istream_iterator<char>(), std::ostream_iterator<char>(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.

jalf
Why is the second parameter an ostream_iterator?
rlbond
er, it isn't! :)(just fixed it. It was a typo)
jalf
A: 

You need to read from it, and then output what you read:

istream stm;
string str;
stm >> str;
cout << str;
1800 INFORMATION
that only reads one word (whitespace delimited). I think he wants to copy everything from the stream.
jalf
I think if he wanted that, he would have said it
1800 INFORMATION
Who knows what he wants, the question is poor.
Brian Neal
A: 

You ouput the istream's streambuf.

For example, to output an ifstream to cout:

std::ifstream f("whatever");
std::cout << f.rdbuf();
Éric Malenfant