字符串流的定义
字符串流是以内存中的string对象或字符数组( C风格字符串) 为输入输出的对象, 将数据输出到内存中的字符串存储区域, 或者从字符串存储区域读入数据
字符串流的作用
字符串流的作用是利用输入输出操作方式将各种类型的数据转换成字符序列,或者相反。由于计算机物理的或逻辑的设备大多数能处理的据是字符序列( 或字节序列),因此字符串流就是程序数据与设备进行数据交换重要的桥梁
字符串流的分类
字符串流类有( istringstream、 ostringstream、 stringstream) 和( istrstream、 ostrstream、 strstream) 两种。 前一种以C++ string串对象作为字符串, 定义在头文件中; 后一种以字符数组作为字符串( 即C风格字符串) , 定义在头文件中。根据C++标准的定义, strstream是过时的, 未来版本的C++标准可能不再支持strstream。
字符串流的使用方法
使用字符串流类的方法是建立字符串流对象, 通过构造函数或成员
函数str()与某个字符串关联, 此后对字符串流对象按输入输出形式
进行操作。 字符串流类的构造函数和常用成员函数原型如下:
istringstream(openmode which=ios_base::in); //构造字符串输入流对象
//构造字符串输入流对象, 并初始化为str的内容
istringstream(const string & str,openmode which=ios_base::in);
ostringstream(openmode which=ios_base::out); //构造字符串输出流对象
//构造字符串输出流对象, 并初始化为str的内容
ostringstream(const string& str,openmode which=ios_base::out);
stringstream(openmode which=ios_base::out|ios_base::in); //构造字符串输入输出流对象
//构造字符串输入输出流对象, 并初始化为str的内容
stringstream(const string & str,openmode which=ios_base::out|ios_base::in);
string str(); //返回当前字符串流缓冲区关联的字符串对象的副本
void str(const string & s); //复制字符串s内容到字符串流缓冲区关联的string对象中
ostringstream
ostringstream 对象用来进行格式化的输出, 可以将各种类型
转换为string类型, 只支持 << 操作符, 如:
ostringstream oss;
oss<<1.234; //double型转化为字符串
oss<<" "; //字符串常量转化为字符串
oss<<1234; //int型转化为字符串
oss<<endl;
cout<<oss.str(); //输出“1.234 1234”
oss.str(""); //每次使用前清空
oss<<3.114159; //double型转化为字符串
Str2=oss.str();
cout<<Str2<<endl; //输出“3.14159”
istringstream
istringstream 对象用于把一个已定义字符串中的以空格隔开
的内容提取出来, 只支持 >> 操作符, 如:
int a;
string str1;
string input="abc 123 def 456 ghi 789";
istringstream iss(input); //通过构造函数对iss进行赋值
while(iss>>str1>>a) cout<<str1<<" "<<a<<endl;
运行结果:
abc 123
def 456
ghi 789
stringstream
stringstream类是istringstream和ostringstream类的综合, 支
持<<和>>操作符。
int a; string str1;
string input="abc 123 def 456 ghi 789";
stringstream ss;
ss<<input;
while(ss>>str1>>a) cout<<str1<<" "<<a<<endl;
运行结果:
abc 123
def 456
ghi 789
应用例子
数字的加减法:
#include <iostream>
#include <sstream> //字符串流的一些类的定义全部放在这个头文件里
using namespace std;
int main()
{
string s1, s2;
ostringstream oss;//字符串输出流
istringstream iss;//字符串输入流
char c1 = '+', c2;
double val, sum = 0.0;
cout << ("please input an add/sub claculate");
cin >> s2;
iss.str(s2);//iss在读取和解析时是以空白字符作为分隔符(俩字符串之间空格隔开)
while (c1 != ' ')
{
iss >> val >> c2;//读取一个值和运算符
if (c1 == '+') sum = sum + val;
else if (c1 == '-')sum = sum - val;
c1 = c2, c2 = ' ';
}
oss << sum;
s1 = oss.str();//将oss里面字符串输出到
cout << ("The answer is ")<<s1 << endl;
system("pause");
}
运行情况:
please input an add/sub claculate:
10+20-5
The answer is 25