[SOLVED] QTextStream and std::endl



  • Back again with another problem. Seems like this should be easy, but apparently I am doing something wrong. I am trying to write to a file. Here's the code:

    @
    void UsernamePopup::handleOkClicked()
    {
    QString username;
    QString password;

    QFile configFile("config.txt");
    
    username = "Username | " + mUsernameEntry->text();
    
    if(mPasswordEntry->text() == mPasswordCheckEntry->text())
    {
        password = "Password | " + mPasswordEntry->text();
    
        if (configFile.open(QFile::WriteOnly))
        {
            QTextStream out(&configFile);
    
            out << username << std::endl << password << std::endl;
        }
        else
        {
            //Notify user
        }
    }
    else
    {
       //Code to popup window notifying user
    }
    

    }
    @

    The error message I am getting is:
    @
    D:/Coding/QtProjects/SimChat-build-desktop/../SimChat/usernamepopup.cpp:126: error: no match for 'operator<<' in 'out.QTextStream::operator<<(((const QString&)((const QString*)(& username)))) << std::endl'@

    I have looked at some examples online and even in the documentation. As far as I can tell I am doing what the examples show. Thanks for any assistance.



  • There's no operator<< overload for QTextStream that takes a @ostream &(*fun)(ostream &)@ (yes, that's a pointer to a function that takes a reference to ostream and returns a reference to a ostream). Which, by the way, is the type of std::endl.

    But there's a nice operator<< overload for QTextStream that takes a @ QTextStream &(*fun)(QTextStream &) @ which is the type of QTextStream::endl.



  • Ok, I think I understand what you are saying. I changed the lined to:

    @out << username << std::endl << password << std::endl;@

    This compiles, but when I open the .txt file, It is all on one line in notepad. It does show a little "square" (looks like [])for where the newline should begin. However, Gedit for Windows shows them on separate lines. Part of me is wondering if I should just use ofstream instead of QFile, etc. Thanks.

    Edit: Nevermind. This appears to be a quirk with Windows and "\r\n".



  • Are you sure you pasted the right line of code? It's the same as before...

    About the "\r\n" terminator: simply open your QFile with the QIODevice::Text option.



  • Whoops, did not paste the correct line. Ought to be:

    @out << "Username | " << username << endl << "Password | " << password << endl;@

    And thanks for the advice. Worked like a charm.


Log in to reply
 

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