How to add data in .txt line by line



  • I would like to add data in .txt file line by line how could I have tried the following code

    QString filename="Data.txt";
    QFile file( filename );
    if ( file.open(QIODevice::Append) )
    {
    QTextStream stream( &file );
    stream << s<<'\n' << endl;
    }
    For example file data is "Kamianske_Kropyvnytskyi_KharkivKherson_Kryvyi0Rih_Kharkiv_khmelnytskyi"
    but I would like they to be
    "Kamianske_Kropyvnytskyi_Kharkiv"
    "Kherson_Kryvyi0Rih_Kharkiv_khmelnytskyi"
    to read them line by line afterward
    but it add data in the same line, hope your ideas will help me to resolve the problem, thanks.


  • Qt Champions 2017

    Hi
    the << endl; is correct.
    You are most likely using notepad which only likes \r\n

    https://superuser.com/questions/362087/notepad-ignoring-linebreaks

      QString filename = "Data.txt";
      QFile file( filename );
      if ( file.open(QIODevice::Append) ) {
        QTextStream stream( &file );
        for (int cc = 0; cc < 10; ++cc) {
        stream << QString::number(cc) << "\r\n";
        }
      }
    


  • @mrjj the following code resolve the problem
    QString filename="Data.txt";
    QFile file( filename );
    if ( file.open(QIODevice::Append|QIODevice::Text) )
    {
    QTextStream stream( &file );
    stream << s<<'\n';
    }
    file.close();


  • Qt Champions 2017

    Ok. super
    Please mark as solved.

    My notepad must be extra stupid then :)
    alt text


Log in to reply
 

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