[SOLVED]QString append() problem



  • Please help to me in this issue. I'm trying the following code:

    @QString plainText = "atext";
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");

    cout << endl << "TXT: " ;
    unsigned char hh = (unsigned char)plainText.data();
    for (int i = 0; i<plainText.size();i++)
    cout << hh[i];@

    But now I see just this:TXT: a t e x t a a a
    Why not this:TXT: a t e x t a a a a a a a a a a a


  • Moderators

    Hi, and welcome to the Qt DevNet!

    [quote]
    @
    unsigned char hh = (unsigned char)plainText.data();
    @
    [/quote]That cast is illegal. QString::data() returns (QChar*), which is not (unsigned char*)! It's also why you see spaces in your output.

    The correct conversion is
    @
    cout << endl << "TXT: " << plainText.toStdString() << endl;
    @

    Then your output will be
    @
    TXT: atextaaaaaaaaaaa
    @

    I recommend you read through the QString documentation: http://qt-project.org/doc/qt-5/QString.html



  • Thanks for the reply. You're right.
    The correct conversion is : @cout << endl << "TXT: " << plainText.toStdString() << endl;@
    And I tried the following code and it is work perfect:

    @ QString plainText = "atext";
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");
    plainText.append("a");

    QByteArray newB;
    newB.insert(0,plainText);
    QFile file("in.txt");
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text))
    cout << "File open error";
    file.write(newB);
    file.close();@
    And now I see in in.txt:atextaaaaaaaaaaa
    So that is illegal: @unsigned char hh = (unsigned char)plainText.data();@


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.