流(stream)为C++的输入输出操作提供了许多的便利,通常我们使用的流是std::out用于输出,使用std::cin用于接收用户的输入,除此之外,C++还提供了文件流用于实现文件的读写操作,字符串流用于进行字符串的操作。
C++提供的流(stream)包括三种类型:用于控制台输入、输出的流、用于文件操作的文件流和用于字符串处理的字符串流。
(1)基于控制台的流
istream: 用于从流中读取内容;
ostream: 用于将内容写到数据流中;
iostream: 用于对流进行读写,从istream和ostream派生;
它们包含在iostream头文件中。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int x;
string str;
cin>>x;
cin>>str; //遇到空白符结束
cout<<str<<endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
int x;
string str;
//cin>>x;
//cin>>str; //遇到空白符结束
//cout<<str<<endl;
//对于像“12 33 yyu”这种字符串应该如下操作
getline(cin,str);
cout<<str<<endl;
return 0;
}
控制台格式化输入输出最好用scanf()和printf(),具体格式用法见
C++中printf和scanf的用法 - 阿牧路泽 - 博客园www.cnblogs.com(2)用于文件读写的文件流
ifstream:用于从文件中读取,由istream派生而来;
ofstream:用于将内容写到文件中去,由ostream派生而来;
fstream: 实现文件的读写操作,有iostream派生而来;
它们包含在头文件fstream中。
实际上,文件类型可以分为两种: 文本文件和二进制文件。ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间。
文本文件保存的是可读的字符, 而二进制文件保存的只是二进制数据。利用二进制模式,你可以操作图像等文件。用文本模式,你只能读写文本文件。否则会报错。
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string fname="test.txt";
ofstream fout; //写入文件流对象
fout.open(fname,ios::out);
if(!fout){
cout<<"文件不能打开"<<endl;
}
else{
//输出到磁盘文件
fout<<"Learning C++ is very useful."<<endl;
fout.close();
ifstream fin("test.txt");
if(!fin){
cout<<"文件不能打开"<<endl;
}
else{
string str;
getline(fin,str);
cout<<str<<endl;
fin.close();
}
}
return 0;
}
其他内容可以参考
(转载)C++ ofstream和ifstream详细用法www.cnblogs.com(3)基于字符串I/O操作的字符串流
istringstream: 实现从字符串(string)对象中读取内容,由istream派生而来;
ostringstream: 实现将内容写到字符串(string)对象中,由ostream派生而来;
stringstream: 实现string对象的读写操作,由iostream派生而来;
它们包含在头文件sstream中。
通常,我们可以使用istringstream实现字符串到其它类型数据的转换。
#include<string>
#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
int main(){
istringstream iss;
string str="32 249 7 56";
iss.str(str); //对iss进行赋值,把str字符串存入字符串流中
int val;
vector<int> x;
while(iss>>val){
x.push_back(val);
}
for(auto m: x ){
cout<<m<<" ";
}
cout<<endl;
return 0;
}
#include<string>
#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
int main(){
istringstream istr("1 56.7");
cout<<istr.str()<<endl;//直接输出字符串的数据"1 56.7"
string str=istr.str();//函数str()返回一个字符串
cout<<str<<endl;
int n;
double d;
//以空格为界,把istr中的数据取出来,并进行类型转换
istr>>n;
istr>>d;
cout<<n<<endl;//1
cout<<d<<endl;//56.7
istr>>d;
istr>>n;
cout<<d<<endl;//1
cout<<n<<endl;//56
return 0;
}
其它参考
字符串流 istringstream 和 ostringstream 的用法vcsos.com