QT  - 讨论区

标题:Qt Tutorial 007:使用QTextStream读写文

2014年02月21日 星期五 09:01

QTextStream相当于C++标准库的iostream,使用方法也很类似,提供了<<和>>等方便的操作符。

The QTextStream class provides a convenient interface for reading and writing text.

QTextStream can operate on a QIODevice, a QByteArray or a QString. Using QTextStream's streaming operators, you can conveniently read and write words, lines and numbers. For generating text, QTextStream supports formatting options for field padding and alignment, and formatting of numbers. Example:

编程示例如下:

#include <QCoreApplication>
#include <QTextStream>
#include <QString>
#include <QFile>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextStream qout(stdout);
    qout << "Hello Qt!" << endl;

    QFile file("C:/Qt/Projects/007_QTextStream/test.txt");
    if(!file.open(QIODevice::WriteOnly)) {
        qout << "Can not open file" << endl;
        return -1;
    }
    QTextStream qfile(&file);
    qfile << "Hello World\r\n";
    for(int i=0;i<100;i++) {
        qfile << i << " ";
    }
    qfile << "\r\n";
    for(int i=0;i<100;i++) {
        qfile << hex << i << " ";
    }
    qfile << "\r\n";
    for(int i=0;i<100;i++) {
        qfile << bin << i << " ";
    }
    qfile.flush();
    file.close();
    return a.exec();
}

参考资料:

http://qt-project.org/doc/qt-5.0/qtcore/qtextstream.html

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2024

    京ICP备05028076号