C++文件流读写

被用来读取/写入文件、连接网络和字符串,它的一个有用的特性是易于从混合数据类型中得到字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<sstream>
#include<fstream>
int main() {
using namespace std;
ostringstream strbuf; //字符流声明
int lucky = 7;
float pi = 3.14;
double e = 2.71;
cout << "an in-memory stream" << endl;
strbuf << "lucknumber" << lucky << endl//将各种类型的值和字符串一起传给字符流,然后再做统一处理
<< "pi:" << pi << endl
<< "e:" << e << endl;
string strval = strbuf.str();//将字符串流转换成字符串
cout << strval;//打印字符串
ofstream outf;//声明openfile对象
outf.open("mydata");//打开文件,没有则创建
outf << strval;//将字符串流输出给文件
outf.close();//关闭文件
cout << "read data from the file" << endl;//读文件
string newstr;
ifstream inf;//声明一个输入文件流对象
inf.open("mydata");//打开文件
if (inf) {//Make sure the filr exists before attempting to read
while (! inf.eof()) {//文件流每次读取为一行,读取后会自动进入下一行,直到inf.eof()
getline(inf, newstr);//把读取的每行当做字符串处理
cout << newstr << endl;
}
inf.close();
}
cin.get();
return 0;
}

QT中实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<QTextStream>
#include<QString>
#include<QFile>
QTextStream cout(stdout);
QTextStream cerr(stderr);
int main()
{
QString str,newstr;//Qstring为QT中的string,有丰富的API更好用
QTextStream strbuf(&str);//QT的字符流声明
int lucky =7;
float pi =3.14;
double e=2.71;
cout<<"A in-memory stream"<<endl;
strbuf<<"luckynumber:"<<lucky<<endl//一样先把字符都输入到字符流中,方便后面统一处理
<<"pi:"<<pi<<endl
<<"e:"<<e<<endl;
cout<<str;
QFile data("mydata");//创建QT文件类对象,并用文件初始化QFile对象
data.open(QIODevice::WriteOnly);//打开文件,以QTIO的写方式
QTextStream out(&data);//这里和VC不太一样,要输出到文件,先要将文件转换成对应的字符串流
out<<str;//输出到已绑定字符流文件
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;
}

小试QT GUI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include<QtGui>
#include<QMessageBox>
#include<QInputDialog>
#include <QApplication>
int main(int argc,char* argv[]){
QApplication app(argc,argv);
QTextStream cout(stdout);
int answer = 0;
do{
int factArg=0;
int fact(1);
factArg = QInputDialog::getInt(0,"Factorial Calculator","Factorial of:",1);//QT的输入对话框
cout<<"User entered:"<<factArg<<endl;//打印到控制台
//业务内容
int i =2;
while(i<=factArg){
fact=fact*i;
++i;
}
QString response=QString("The factorial of %1 is %2.\n%3")
.arg(factArg).arg(fact)
.arg("Do you want to computer another factorial?");//Qstring格式化字符串内容
answer=QMessageBox::question(0,"play again?",response,
QMessageBox::Yes|QMessageBox::No);//对话框设置
}while(answer==QMessageBox::Yes);
return EXIT_SUCCESS;
}

QString

可以将char类型的字符串用等号之间转换过来

1
2
3
4
5
6
7
8
9
10
11
#include<QTextStream>
#include<QString>
int main()
{
const char* charstr="this is a char string";
QTextStream cout(stdout);
QString str=charstr;
cout<<str<<endl;
return 0;
}
坚持原创技术分享,您的支持将鼓励我继续创作!