Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to read only first words from each line of file and add them to another file?



  • Hello. I have a

    Qfile myfile("a.txt");
    

    which contents:
    a 123
    b 123
    c 123

    I want to add only a, b, c to my another file;
    Tryied to do it in this way:

        QFile myfile("a.txt");
        myfile.open(QIODevice::ReadOnly | QIODevice::Text);
    
        QTextStream out(&myfile);
    
        QString text;
        QStringList split1;
    
        while(!out.atEnd())
        {
            text = out.readLine();
            split1.append(text.split(" "));
    
        }
        myfile.close();
    
        QFile myfile2("b.txt");
    
        if(myfile2.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&myfile2);
            out << split1.join("\n");
    
        }
        else
            QMessageBox::information(this," ", " - ");
    
        myfile2.close();
    

    and fully understood, that I just delete every space " " and separate words from lines. Pls help.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    If you only what the first word why not split1.append(text.split(" ").first()); ?



  • @SGaist
    Oh. I didn`t notice this :)
    Thank you a lot.


  • Lifetime Qt Champion

    You're welcome !

    Since you have it working know, please mark the thread as solved using the "Topic Tools" button so that other forum users may know a solution has been found :)


Log in to reply