简体   繁体   English

std :: ostream到QString?

[英]std::ostream to QString?

Is there a way to convert an std::ostream to a QString? 有没有办法将std :: ostream转换为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: 允许我扩展,以防它有用:我正在用C ++ / Qt编写一个程序,我曾经(不)通过使用std :: cout来处理/调试异常,例如:

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: 现在我想把错误作为QStrings抛出并稍后捕获它们,所以我现在写了:

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: 我的问题是我一直在重载运算符<<以便我可以将它与许多对象一起使用,例如Bird ,所以我实际上写了:

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? 有没有办法可以把它作为QString抛出? 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 ,如下所示:

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 . 具体来说, std::stringstream::str成员函数将为您提供一个std::string ,然后您可以将其传递给QString::fromStdString静态成员函数以创建QString

The std::stringstream class can receive input from overloaded << operators. std::stringstream类可以从重载的<<运算符接收输入。 Using this, combined with its ability to pass its value as a std::string , you can write 使用它,结合它将其值作为std::string传递的能力,你可以写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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