stringstream

来源:互联网 发布:社交网络用英语怎么说 编辑:程序博客网 时间:2024/05/18 06:41

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"); 
}


作者Blog:http://blog.csdn.net/packe_peng_520/