Std :: ostream for QString?
Is there a way to convert std :: ostream to QString?
Let me expand if helpful: I am writing a program in C ++ / Qt and I have used (not) exception handling / debug just using std :: cout, like 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 wrote instead:
throw(QString("Error in void Cat::eat(const Bird &bird): bird has negative weight"));
My problem is that I was overloading the <<operator so that I can use it with many objects like a Bird
, so I would actually write:
std::cout << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
Is there a way I can do this now as a QString? I would like 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 won't work. What should I do?
source to share
You can use std::stringstream
like this:
std::stringstream out;
// ^^^^^^
out << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
throw(QString::fromStdString(out.str()));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
In particular, a member function std::stringstream::str
will deliver to you std::string
, which you can pass into a static member QString::fromStdString
to create QString
.
source to share
The class std::stringstream
can receive input from overloaded operators <<
. Using this, combined with its ability to convey its value as 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()));
}
source to share