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

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

 基本思想:

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

 

优点:简单。。。

 

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

 

写流(out):

 

读流(in):

 

二。用二个缓冲区。。

 

代码:

 

 

// dffffffff.cpp : Defines the entry point for the console application.
//
#include <StdAfx.h>
#include   <iostream> 
#include   <locale> 
#include   <fstream>
#include <string> 
#include <sstream>
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)<<s<<endl;
	//pof->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<<ms;
	}
	MyWrite("12345");
	MyWrite("23333333312");
	MyWrite("sdafa");
    while(MyRead(ms)){
		cout<<ms;
	}
	return 0;
}

    

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

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

 #include <iostream>  
#include <sstream>  
#include <string>  
using namespace std;  
  
int main()   
{  
    stringstream ostr("ccc");  
    ostr.put('d');  
    ostr.put('e');  
    ostr<<"fg";  
    string gstr = ostr.str();  
    cout<<gstr<<endl;  
  
    char a;  
    ostr>>a;  
    cout<<a  
      
    system("pause");  
}

  除此而外,stringstream类的对象我们还常用它进行string与各种内置类型数据之间的转换。 

  示例代码如下:

 #include <iostream>  
#include <sstream>  
#include <string>  
using namespace std;  
  
int main()   
{  
    stringstream sstr;  
//--------int转string-----------  
    int a=100;  
    string str;  
    sstr<<a;  
    sstr>>str;  
    cout<<str<<endl;  
//--------string转char[]--------  
    sstr.clear();//如果你想通过使用同一stringstream对象实现多种类型的转换,请注意在每一次转换之后都必须调用clear()成员函数。  
    string name = "colinguan";  
    char cname[200];  
    sstr<<name;  
    sstr>>cname;  
    cout<<cname;  
    system("pause");  
}

 

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