stringstream的基本用法

来源:互联网 发布:linux windows samba 编辑:程序博客网 时间:2024/05/22 06:22


stringstream的基本用法:可以用这个类将不同的数据类型转化为字符

stringstream是字符串流。它将流与存储在内存中的string对象绑定起来。
在多种数据类型之间实现自动格式化。

1.stringstream对象的使用

#include<sstream>#include<iostream>using namespace std;int main(){    string line,word;    while(getline(cin,line))    {        stringstream stream(line);        cout<<stream.str()<<endl;        while(stream>>word){cout<<word<<endl;}    }    return 0;}

输入:shanghai no1 school 1989
输出:shanghi no1 school 1989
shanghai
no1
school
1989

2.stringstream提供格式化转换程序(即,将数字和字符串之间进行转换):

#include<sstream>#include<iostream>using namespace std;int main(){    int val1 = 512,val2 =1024;    stringstream ss;    //“val1: "此处有空格,字符串流是通过空格判断一个字符串的结束    ss<<"val1: "<<val1<<endl<<"val2: "<<val2<<endl;    cout<<ss.str();    string dump;    int a,b;    ss>>dump>>a>>dump>>b;    cout<<a<<b<<endl;    return 0;}

输出为:val1: 512
    val2: 1024
    512 1024
第一处黑体字部分:将int类型读入ss,变为string类型
第二处黑体字部分:提取512,1024保存为int类型。当然,如果a,b声明为string类型,那么这两个字面常量相应保存为string类型
3.其他注意
stringstream不会主动释放内存(或许是为了提高效率),但如果要在程序中用同一个流,反复读写大量的数据,将会造成大量的内存消 耗,因些这时候,需要适时地清除一下缓冲 (用 stream.str(“”) )

#include <cstdlib>#include<iostream>#include<sstream>using namespace std;int main(){    stringstream ss;    string s;    ss<<"shanghai no1 school";    ss>>s;    cout<<"size of stream = "<<ss.str().length()<<endl;    cout<<"s: "<<s<<endl;    ss.str("");    cout<<"size of stream = "<<ss.str().length()<<endl;}

输出:
size of stream = 19
s: shanghai
size of stream = 0

4 如果要从txt中读取文件,比如一个txt中有3行:
1feature 112:0.5
2feature 1222:0.2
3feature 1:0.1
要从该txt中读取每个冒号之前的数据那么可以这样:

ifstream fin("data.txt");string s;string subs;vector<int> ints;int tmp;while(getline(fin,s,'\n'))//getline函数默认是以\n作为一次读取的字符串多少{    int pos0 = s.find(' ');    int pos1 = s.find(':');    subs = s.substr(pos0,pos1);    stringstream strs(subs);    strs>>tmp;    ints.push_back(tmp);}
0 0
原创粉丝点击