0

I have a statement like such that is meant to output what the function returns.

std::cout<<"result: " << calculateAvg(someArray, size) << std::endl;

The function however, outputs things itself before it returns the value. Is there a way for me to print out what is returned on that line, instead of after everything that is printed by the function?

Fianite
  • 319
  • 2
  • 9
  • 2
    Not unless you rewrite the function. – David Hoelzer Jan 19 '16 at 21:06
  • 1
    Assign the result to a temporary variable to ensure any output by the function is before "result: " – pticawr Jan 19 '16 at 21:08
  • You should also realize that `<<` is just syntactic sugar for a call to `operator<<(...)`. So you just have a nested function call, of which the inner ones must be evaluated before the outer ones. – vsoftco Jan 19 '16 at 21:13

2 Answers2

3

Is there a way for me to print out what is returned on that line, instead of after everything that is printed by the function?

No. The function has to run before it can return something. This means any output the function outputs will come before the output of the functions' return value.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • [Not entirely true](http://stackoverflow.com/a/34886998/1413395) regarding the OP's intend. – πάντα ῥεῖ Jan 19 '16 at 21:28
  • @πάνταῥεῖ my take from reading the question was the OP did not want to change the `cout` line. But yes if he is okay with changing the call site then he can redirect `cout` – NathanOliver Jan 19 '16 at 22:18
3

You can redirect std::cout to a buffer (see this post), call the function, redirect back, print result and then print the buffer:

#include <iostream>
#include <sstream>
#include <string>

std::string myFunc() {
    std::cout << "print inside myFunc" << std::endl;
    return "string returned from myFunc";
}

int main() {
    std::stringstream print_inside;
    std::streambuf * old = std::cout.rdbuf(print_inside.rdbuf());
    std::string returned_string = myFunc();
    std::cout.rdbuf(old);

    std::cout << returned_string << std::endl;
    std::cout << print_inside.str() << std::flush; //endl already there
}
Community
  • 1
  • 1
Adam Trhon
  • 2,915
  • 1
  • 20
  • 51