【问题标题】:std::ostream to QString?std::ostream 到 QString?
【发布时间】:2015-09-04 20:38:00
【问题描述】:

有没有办法将 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,然后在QString的构造函数中使用ss.str()? IE。 throw(QString(ss.str()));
  • 应该是QString::fromStdString(ss.str()) - 抱歉

标签: c++ qt exception


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    std::stringstream 类可以接收来自重载的&lt;&lt; 运算符的输入。使用它,再加上它能够将其值作为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()));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多