c++一日一练:利用流来实现读和写的同步(原创)

int main(int argc,char*argv[])
{
	 string s;
     stringstream ssm;
	 //ssm.rdbuf();
	 //写到流的缓冲区,,但是并不刷新。
	 ssm<<"hello分隔符!";
	 //从流读,实际上是从缓冲区读。
	 //读完之后缓冲区数据没了。
	 cout<<(bool)(ssm>>s);
	 //这句话如果没有,那么将导致如下情况:
	 //如果缓冲区在输出没有刷新的情况下被读取了。。
	 //那么将会视为错误。
	 //当前缓冲区被标记为不可用。
	 //所以要清楚这个状态。让它永远可用。
	 ssm.clear();
	 cout<>s;
	 cout<

 基本思想:

一.用一个缓冲区来实现读写

 

优点:简单。。。

 

缺点...必须保证写流缓冲并不往写流刷新,而且读和写共享一个缓冲区,这在没有中间媒介的情况下很有用。(例如不需要写入文件)

 

写流(out):

 

读流(in):

 

二。用二个缓冲区。。

 

代码:

 

 

// dffffffff.cpp : Defines the entry point for the console application.
//
#include 
#include    
#include    
#include   
#include  
#include 
using namespace std;
//创建全局对象。这些对象保存在全局区。
string line;
stringstream *pof=new stringstream(line);
ostream *pOut=new ostream(pof->rdbuf());	
//stringstream* pif=new  stringstream("ddddddddddddddddddddddd");
istream *pIn=new istream(pof->rdbuf());
void MyWrite(string s){
	(*pOut)<close();
}
bool MyRead(string &sr){
    /*********************输出,从文件读数据********************************************/
    //创建输入缓冲

	//绑定(输入)
	pIn->tie(pOut);
	return (*pIn)>>sr;
	//pIn->clear();
	//ifs.close();
}

int main(int argc, char* argv[])
{	
    MyWrite("12345");
	MyWrite("23333333312");
	MyWrite("sdafa");
	string ms;
    while(MyRead(ms)){
		cout<

    

对于了来说,不用我多说,大家也已经知道它是用于C++风格的字符串的输入输出的。 
  stringstream的构造函数原形如下: 

  stringstream::stringstream(string str);
  示例代码如下:

 #include   
#include   
#include   
using namespace std;  
  
int main()   
{  
    stringstream ostr("ccc");  
    ostr.put('d');  
    ostr.put('e');  
    ostr<<"fg";  
    string gstr = ostr.str();  
    cout<>a;  
    cout<  
#include   
#include   
using namespace std;  
  
int main()   
{  
    stringstream sstr;  
//--------int转string-----------  
    int a=100;  
    string str;  
    sstr<>str;  
    cout<>cname;  
    cout<

 

你可能感兴趣的:(C,C#,C++)