您的位置:首页 > 编程语言 > Qt开发

QTextStream

2010-05-10 13:13 176 查看
QTextStream 像是一个适配器,能支持多数据源

#include <QTextStream

>

#include <QString

>

#include <QFile

>

QTextStream

cout(stdout, QIODevice::WriteOnly);

QTextStream

cerr(stderr, QIODevice::WriteOnly);

int main() {

QString

str, newstr;

QTextStream

strbuf(&str); //使用QString做数据源

int lucky = 7;

float pi = 3.14;

double e = 2.71;

cout << "An in-memory stream" << endl;

strbuf << "luckynumber: " << lucky << endl

<< "pi: " << pi << endl

<< "e: " << e << endl;

cout << str;

QFile

data("mydata");

data.open(QIODevice::WriteOnly);

QTextStream

out(&data);
//使用QDevice做数据源

out << str ;

data.close();

cout << "Read data from the file - watch for errors." << endl;

if(data.open(QIODevice::ReadOnly)) { /*Make sure the file exists before

attempting to read.*/

QTextStream

in(&data);

int lucky2;

in >> newstr >> lucky2;

if (lucky != lucky2)

cerr << "ERROR! wrong " << newstr << lucky2  << endl;

else

cout << newstr << " OK" << endl;

float pi2;

in >> newstr >> pi2;

if (pi2 != pi)

cerr << "ERROR! Wrong " << newstr << pi2 << endl;

else

cout << newstr << " OK" << endl;

double e2;

in >> newstr >> e2;

if (e2 != e)

cerr << "ERROR: Wrong " << newstr << e2 <<  endl;

else

cout << newstr << " OK" << endl;

data.close();

}

cout << "Read from file line-by-line" << endl;

if(data.open(QIODevice::ReadOnly)) {

QTextStream

in(&data);

while (not in.atEnd()) {

newstr = in.readLine();

cout << newstr << endl;

}

data.close();

}

return 0;

}

评注:从上面的例子可以看出,QTextStream不负责文件的打开与创建,仅仅提供文件访问的方法,实现了功能的独立性

,由于它支持多数据,不区分读写的方向,比fstream流使用起来更加方便
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: