Re: ostream outputting garbage
dev_15 wrote:
Hi, i have the following program to display the input received
separated into any word that has Uppercase letters and all lowercase
words.
For the following input "Upper lower" i get the following
output on the console
Upper
0002A634lower
0002A634
I was expecting just
Upper
lower
Why am i getting the print of some memory address presumably, code
below:
I didn't look all that carefully at your code, but please consider:
std::ostream &operator<<(std::ostream &o,
const std::vector<std::string> &v);
and the line
std::cout << v;
probably produces some code that we can think of like this:
operator<<(std::cout, v);
whereas
std::ostream &write(std::ostream &o, const std::vector<std::string> &v);
and the line
std::cout << w(std::cout,v);
probably produces some code that we can think of like this:
operator<<(std::cout, write(std::cout,v));
In this case, the call to write will, if written like your code, write
out each element of v to std::cout and then return a reference to
std::cout. The call to operator<< will write out the 'value' of the
reference. I'm going to guess and say that somehow this reference
decays into a pointer of some kind. I'm probably not technically correct
about that.
You may want to play with this example and see if it clarifies things.
#include <iostream>
const int *p(std::ostream &o, const int &t) {
o << "*" << t << "*" << std::endl;
return &t;
}
int main() {
const int a = 55;
std::cout << "$" << p(std::cout, a) << "$" << std::endl;
std::cout << "#" << &a << "#" << std::endl;
}
LR