简体   繁体   中英

std::ostream printing address at end of function

I have the following function:

std::vector<double>residuals;
std::cout << Print_res(std::cout);
std::ostream& Print_res(std::ostream& os) const {

  os << "\tresidual" << std::endl;
  for (unsigned int i = 0 ; i < 22 ; i++) {
    os << "\t\t" << residuals[i] << std::endl;
  }
  os << std::flush;
  return os;
};

It prints the residuals correctly, but at the end of the output tags an address as follows:

2275
2279.08
2224.0835
0x80c5604

how do I fix this? EDIT: after reading everyone's comments I replaced the call to the function Print_res with a std::copy as

 std::copy(residuals.begin(), residuals.end(), std::ostream_iterator<double>(std::cout,"\n"));

and that did not print the address, so I presume there is something wrong in the way I have written the function.

std::cout << Print_res(std::cout);

This is not legal at global scope so the code that you have posted is not valid. If this statement were executed from, say, a function then Print_res would be called and then the return value of Print_res would also be streamed to std::cout . This is most likely not what you meant. You probably want just this:

Print_res(std::cout);

Your statement performs the equivalent of:

std::cout << std::cout;

In C++03 (which you must be using), std::cout has an operator void* (from std::basic_ios<char> ) the result of which is what is being printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM