sstream定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。
为什么要用stringstream?
因为用sprintf()函数将一个变量从int类型转换到字符串类型。为了正确地完成这个任务,你必须确保证目标缓冲区有足够大空间以容纳转换完的字符串。此外,还必须使用正确的格式化符。如果使用了不正确的格式化符,会导致非预知的后果。
stringstream 常见用法
1、数据类型转换
例如:int 类型转换为 string 类型(部分代码)
string result=”10000”;
int n=0;
stream<<result;
stream>>n;//n等于10000
2、识别出一行字符串中的多个单词
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string str("How are you? 123 1 4.368");
stringstream ss(str);
cout<<ss.str()<<endl;
string tmp;
for(int i=0;i<6;i++){
ss>>tmp;
cout<<tmp<<endl;
}
return 0;
}
或者用getline()获取一行字符串,stringstream识别出一行字符串中的多个单词
string line,x;
getline(cin,line);
stringstream ss(line);
while(ss>>x)
cout<<x<<endl;