1

I'm new to C++ and I encountered a case where a script directly prints an output to prompt like this:

cout << setw(10) << Object->GetAuthor().GetId() << " ";
cout << Object->GetDate() << " ";
cout << Object->GetCaseNumber() << " ";

This works in the script and prints to the console, now I would like to save the strings instead of printing it to prompt but the fact is that this are not strings in this sample they could be int variable or other things.

I don't understand why cout << Object->GetType() << " "; works while string x = Object->GetType() doesn't.

And is there a way to save what's being printed to the console as strings?

2
  • What does GetType return? The simple answer is that cout::operator<< can accept that type, but no string constructor can. If all else fails there is std::stringstream Commented Nov 16, 2014 at 23:06
  • Replace cout with a stringstream object, and use its str function to extract the completed string. Commented Nov 16, 2014 at 23:07

2 Answers 2

3

Yes, there are streams that print to strings.

Like this:

#include <sstream>

// ...

std::ostringstream s;
s << setw(10) << Object->GetAuthor().GetId() << " ";
s << Object->GetDate() << " ";
s << Object->GetCaseNumber() << " ";

std::string result = s.str();

The reason

string x = Object->GetType()

doesn't work is that Object->GetType() doesn't return something that can be assigned to a string.

The << operator "knows" how to convert many things to a string representation (the technical term is that it is overloaded for numerous different types).

Sign up to request clarification or add additional context in comments.

Comments

0

Cout << knows about several types it can print, such as int, string and bool. It can also print object addresses if it doesn't know how to handle those objects.

The problem here is that string isn't that clever so the conversion may not work. You need to make sure that GetType returns something that can be converted to a string properly

5 Comments

That's not a helpful solution. Why not recommend stringstream?
If GetType returns an object, Springsteen won't help
It returns an object that supports operator << with a stream so probably it will.
It will probably print the object address
No it will call operator << on the object or refuse to compile. If it works with cout it will work with streamstream unless the operator is implemented in an unusual way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.