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
  • 8

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
  • 161,918
  • 27
  • 262
  • 366
  • [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,835
  • 1
  • 19
  • 49