Reputation: 3212
Is there a way to convert an std::ostream to a QString?
Allow me to expand in case it is useful: I am writing a program in C++/Qt and I used to (not) deal with / debug exceptions by just using std::cout, as in for example:
std::cout << "Error in void Cat::eat(const Bird &bird): bird has negative weight" << std::endl;
Now I want to throw errors as QStrings and catch them later, so I would now write instead:
throw(QString("Error in void Cat::eat(const Bird &bird): bird has negative weight"));
My issue is that I've been overloading the operator << so that I can use it with many objects, for instance a Bird
, so I would actually have written:
std::cout << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
Is there a way that I can throw this as a QString now? I would like to be able to write something like:
std::ostream out;
out << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
throw(QString(out));
but that doesn't work. What should I do?
Upvotes: 5
Views: 5205
Reputation: 3001
The std::stringstream
class can receive input from overloaded <<
operators. Using this, combined with its ability to pass its value as a std::string
, you can write
#include <sstream>
#include <QtCore/QString>
int main() {
int value=2;
std::stringstream myError;
myError << "Here is the beginning error text, and a Bird: " << value;
throw(QString::fromStdString(myError.str()));
}
Upvotes: 2
Reputation: 76280
You can use an std::stringstream
as follows:
std::stringstream out;
// ^^^^^^
out << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
throw(QString::fromStdString(out.str()));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
Specifically, the std::stringstream::str
member function will get you an std::string
, which you can then pass to the QString::fromStdString
static member function to create a QString
.
Upvotes: 5