C++ 中的 stringstream 类

<sstream>定义了三个类:istringstream,ostringstream,stringstream,分别用来进行流的输入、输出、输入输出操作。

<sstream>主要用来数据类型转换,<sstream>使用string对象代替字符数组snprintf,避免缓冲区溢出,其传入参数和目标对象的类型会被自动推导出来,因此不存在错误的格式化符的问题。安全、自动、直接。

 

数据类型转#include<string>

#include<iostream>
#include<sstream>
#include<stdio.h>
using namespace std;
//数据类型转换 
int main(){
    stringstream sstream;
    string strResult;
    int nValue=1000;
    sstream<<nValue;//利用输出流功能先填充输出缓冲区
//<<运算符常用做输入输出流的插入符,表明输出到
sstream>>strResult;//利用输入流功能依次读缓冲区,赋值给相应的变量
//>>运算符常用作提取符,表明赋值给
cout<<"cout strResult is:"<<strResult<<endl; printf("printf strResult is:%s",strResult.c_str()); return 0; }

结果:

cout strResult is:1000
printf strResult is:1000

多个字符串拼接:

#include<string>
#include<iostream>
#include<sstream>
#include<stdio.h>
using namespace std;
int main(){
    stringstream sstream;
    //将多个字符串放到sstream 
    sstream<<"first"<<" "<<"string,";
    sstream<<" second string";
    cout<<"strResult is:"<<sstream.str()<<endl;//使用 str() 方法,将 stringstream 类型转换为 string 类型
    sstream.str("");//清空sstream 必须使用 sstream.str("")方式;clear()方法适用于进行多次数据类型转换的场景
    sstream<<"third string";
    cout<<"After clear,strResult is:"<<sstream.str()<<endl;
    return 0;
}

结果:

strResult is:first string, second string
After clear,strResult is:third string

stringstream的清空:

#include<string>
#include<iostream>
#include<sstream>
#include<stdio.h>
using namespace std;
int main(){
    stringstream sstream;
    int first,second;
    sstream<<"456";//流入字符串 
    sstream>>first;//转换为int 
    cout<<first<<endl;
    sstream.clear();//在进行多次类型转换前,必须先运行clear() 
    sstream<<true;//流入bool值 
    sstream>>second;//转换为 int 
    cout<<second<<endl;
    return 0; 
}

结果:456 1

 


posted @ 2019-10-29 09:26  一只蒟蒻也有大佬梦  阅读(427)  评论(0)    收藏  举报