简体   繁体   中英

std::ostream to QString?

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?

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 .

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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM