Rhdr
Rhdr

Reputation: 387

How to use the >> operator in a Qt file stream while loop

How do you use the >> input operator in the Qt file stream's while loop? (is it possible instead of making use of fin.atEnd() ?) What I want to do is import word by word instead of whole lines. Here is my code below, I have marked the line in question:

QTextStream cout(stdout);
QTextStream cin(stdin);

int main()
{
    //read & write a string to and from file
    //open input file
    QFile inData("input.txt");
    inData.open(QIODevice::ReadOnly);
    QTextStream fin(&inData); //setup file stream input

    //open ouput file
    QFile outData("output.txt");
    outData.open(QIODevice::WriteOnly);
    QTextStream fout(&outData); //setup file stream output

    QString next;

    //copy one file to another
    while (fin >> next)   ////////////////THIS LINE/////////////
    {
        next = fin.readLine();
        next += '\n';
        fout << next;
    }

    return 0;
}

Thanks?

This question Read word by word from a text file in Qt4 solves the word by word import part, but I still would still like to know if you can use the >> input operator within Qt as shown above. (In standard c++ you can use either fin >> next OR fin.eof())

Upvotes: 3

Views: 1376

Answers (1)

Resurrection
Resurrection

Reputation: 4106

operator>> returns the stream reference:

QTextStream &operator>>(QTextStream &stream, QString &next);

and there is no implicit conversion between QTextStream& and bool. You could however use QTextStream::Status for this like so:

while((fin >> next).status() == QTextStream::Ok)
{
    //...
}

Upvotes: 1

Related Questions