QByteArray to QString to std::stringstream 不起作用

QByteArray to QString to std::stringstream doesn't work

本文关键字:to stringstream 不起作用 std QString QByteArray      更新时间:2023-10-16

任何人都知道的原因

QString Lulu ( data ); //data is a QByteArry ( from a QNetworkrequest ) 
std::stringstream streamedJson ;
   // QString Lulu ( data.data() );
    qDebug()<< "Lulu:" << Lulu; // here it views the right string
    streamedJson << Lulu.toStdString();
    qDebug() << "streamedJson: "<< streamedJson ; // here it views 0x7fffc9d46568

不起作用?为什么不在这里查看字符串?最后,我会解析它,并给出解析后的字符串

boost::property_tree::ptree propertyTree;
            try
            {
                boost::property_tree::json_parser::read_json(streamedJson, propertyTree);
            }
catch(boost::property_tree::json_parser::json_parser_error& ex)
       {
           qDebug() << "ex: "<< ex.what(); // this and Lulu views the same (unparsed) string 
           qDebug ("propertyree error");
       }

目前,它只查看"属性错误"。但它应该在我的控制台中打印解析后的字符串

std::stringstream不能直接与QDebug::operator<<一起使用。您可以显式地将其转换为QString。例如,

qDebug() << "streamedJson: " << QString::fromStdString(streamedJson.str());

streamedJson.str()返回std::string,然后使用QString::fromStdString转换为QString

您的程序打印0x7fffc9d46568可能是因为streamedJson被隐式转换为qDebug可打印对象。或者,程序中的某个地方可能有一个operator<<函数,它将std::stringstream作为输入。

尝试初始化QString变量,如下所述,并尝试将值放入std::string变量,然后再将其推入std::stringstream

QString Lulu = QString(data);
std::stringstream streamedJson ;
std::string strLulu = Lulu.toStdString();
streamedJson << strLulu;
qDebug() << "streamedJson: "<< streamedJson;

希望这能有所帮助。

QString具有函数std::string toStdString() const。也许你应该这样使用它:

streamedJson << Lulu.toStdString();

如果它不起作用,你可以尝试

streamedJson << Lulu.toStdString().c_str();

如果它也不起作用,我们将找到另一个可能的解决方案。祝你好运

编辑:我看了好几份文件,我想我已经解决了你的问题。类std::stringstream具有字符串的内部表示。为了从这个类中获得std::string,您应该使用它的函数str():http://www.cplusplus.com/reference/sstream/stringstream/str/那么你的代码应该是这样的:

string myString = streamedJson.str();
std::cout << myString;

我相信它会起作用的。