0

I have a function which looks like below and I am trying to print out the values in QT.

void myfunction(
    std::string&    Service,
    std::string&    Type,
    std::string&    Hostname,
    std::string&    Address,
    UNUM16      Port,
    std::map< std::string, std::string >& TxtList )
{
    qDebug() << "Hostname capacity is : " << Hostname.capacity();
    qDebug() << "Hostname is : " << QString::fromStdString(Hostname);
    qDebug() << "Port is : " << ntohs(Port);

    std::map< std::string, std::string >::iterator iter;
    iter = TxtList.find("FwVersion");

}

Now when I run the function, first debug statement prints the correct value for capacity of string. But the second debug statement does not work and it just prints empty string. And also the when I do the find on map, the application just crashes.

I have also tried QString::fromUtf8(Hostname.c_str()) function and even that did not work

Is there anyway to convert the values and print them in QT?

13
  • Shouldn't be passing std::string as a reference usually. It has its own copy constructor. Commented Jul 17, 2014 at 15:27
  • 2
    @Qix, Passing it by const reference is common. By non-const reference should hold to the same rules as passing anything else by non-const reference: if you need to change it and propagate those changes. Commented Jul 17, 2014 at 15:28
  • @devana, Please post an MCVE with strings that give the behaviour you describe. Commented Jul 17, 2014 at 15:28
  • @chris they're not passing by const reference though. Commented Jul 17, 2014 at 15:29
  • 1
    @chris The above function is a callback function from a library I am using. I have to use the std::string reference itself as input parameter and I can not change the signature of the function. I have tried without the reference by creating a variable as value type and using QString::fromstdstring works in that case. But not when the string as declared as refernece. Commented Jul 17, 2014 at 15:42

1 Answer 1

2

From qt documentation

QString QString::fromStdString ( const std::string & str ) [static]

Returns a copy of the str string. The given string is converted to Unicode using the fromAscii() function. This constructor is only available if Qt is configured with STL compatibility enabled.

You should not use QString::fromUtf8() as std::string are not UTF8 encoded (unless you put that encoded string there somehow)

Sign up to request clarification or add additional context in comments.

1 Comment

std::string allows for UTF8 encoding, sure. ASCII is inherently UTF8 encoded, and UTF8 allows for proper null-terminated strings. Calling QString::fromUtf8() with an std::string is perfectly okay.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.