Function that prints something to std::ostream and returns std::ostream?
Posted
by dehmann
on Stack Overflow
See other posts from Stack Overflow
or by dehmann
Published on 2009-07-06T16:28:43Z
Indexed on
2010/04/08
3:13 UTC
Read the original article
Hit count: 387
I want to write a function that outputs something to a ostream
that's passed in, and return the stream, like this:
std::ostream& MyPrint(int val, std::ostream* out) {
*out << val;
return *out;
}
int main(int argc, char** argv){
std::cout << "Value: " << MyPrint(12, &std::cout) << std::endl;
return 0;
}
It would be convenient to print the value like this and embed the function call in the output operator chain, like I did in main()
.
It doesn't work, however, and prints this:
$ ./a.out
12Value: 0x6013a8
The desired output would be this:
Value: 12
How can I fix this? Do I have to define an operator<<
instead?
UPDATE: Clarified what the desired output would be.
UPDATE2: Some people didn't understand why I would print a number like that, using a function instead of printing it directly. This is a simplified example, and in reality the function prints a complex object rather than an int
.
© Stack Overflow or respective owner