[英]std::ostream to QString?
有没有办法将std :: ostream转换为QString?
允许我扩展,以防它有用:我正在用C ++ / Qt编写一个程序,我曾经(不)通过使用std :: cout来处理/调试异常,例如:
std::cout << "Error in void Cat::eat(const Bird &bird): bird has negative weight" << std::endl;
现在我想把错误作为QStrings抛出并稍后捕获它们,所以我现在写了:
throw(QString("Error in void Cat::eat(const Bird &bird): bird has negative weight"));
我的问题是我一直在重载运算符<<以便我可以将它与许多对象一起使用,例如Bird
,所以我实际上写了:
std::cout << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
有没有办法可以把它作为QString抛出? 我希望能够写出如下内容:
std::ostream out;
out << "Error in void Cat::eat(const Bird &bird): bird " << bird << " has negative weight" << std::endl;
throw(QString(out));
但这不起作用。 我该怎么办?
您可以使用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()));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^
具体来说, std::stringstream::str
成员函数将为您提供一个std::string
,然后您可以将其传递给QString::fromStdString
静态成员函数以创建QString
。
std::stringstream
类可以从重载的<<
运算符接收输入。 使用它,结合它将其值作为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.