here is my function
ostream margain(std::string firstWord)
{
ostream x;
x << std::setw(20) << firstWord;
return x;
}
in main I want to use the function as follow
std::cout<< margain("start") << "````````````````````````````````````" << std::endl;
// print things out
//then
std::cout<< margain("End") << "````````````````````````````````````" << std::endl;
I get the output, start or end is not shown, and the return value is
0````````````````````````````````````
how can I fix it? and why?
Edit: I know that the function is what causing that, because if I add this
cout << std::setw(20) << firstWord; in the function, It prints right,
I fixed it, not the best way, but as
calling the function as
margain(std::cout, "End") << "~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~" << endl;
the function looks like
ostream& margain(ostream& stream, std::string firstWord)
{
stream << std::left << std::setw(10) << firstWord;
return stream;
}
anyone know better way?
You are printing the value of the ostream, not value of
firstword. Theostream xin this case is an unopened stream, so it doesn't "do" anything. Because the compiler allows to conversion to eitherbool(C++11) orvoid *(before C++11), the "value" from that conversion is printed. Note that any operations onxwill not affectcout.The easiest solution, I would think is to actually add
std::setw(20)to your output line:The other choice would be to pass the
std::couttomargain, and return thestd::string, something like this:then you could do:
But it's not exactly flexible or "neat".
The third option is of course to have a
MarginStringclass:Note that this last way is probably not that great either... ;)