![]() ![]() |
|
二级C++输入输出流:字符串流 | |
作者:佚名 文章来源:不详 点击数 更新时间:2008/4/18 14:40:15 文章录入:杜斌 责任编辑:杜斌 | |
|
|
C++ 的 I/O 流库提供了两个类: ostrstream 和 istrstream 。其中, ostrstream 类是从 ostream 类派生出来的,它是用来将不同的信息格式化为字符串,并放到一个字符数组中。 Istrstream 类是从 istream 类派生的,它是用来将文本项转换为变量所需要的内部格式。它们都包含在 stream.h 中。 1、ostrstream 类的构造函数: ostrstream::ostrstream(); ostrstream::ostrstream(char *s,int n,int mode=ios::out); 其中:第一个构造函数是缺省构造函数,它用来建立存储所插入的数据的数组对象。 第二个构造函数带三个参数,其中 s 是字符指针或字符数组,用来存放所插入的字符数据。 n 用来指定这个叔数组最多能存放的字符个数。 Mode 参数给出流的方式。 另外, ostrstream 类还提供如下的成员函数: int ostrstream::pcount(); char *ostrstream::str(); 前一个成员函数的功能是返回流中当前已经插入的字符个数。 后一个成员函数的功能是返回标识存储串的数组对象的指针值。 例 13 :分析下列程序的输出结果: #include<iostream.h> #include<fstream.h> #include<strstream.h> const int N=80; void main() { char buf[N]; ostrstream out1(buf,sizeof(buf)); int a=50; for(int I=0;I<6;I++,a+=10) out1<<”a=”<<a<<”,”; out1<<'\ 0' ; cout<<”Buf:”<<buf<<endl; double PI=3.1415926; out1.setf(ios::fixed|ios::showpoint); out1.seekp(0); out1<<”the value of ip=”<<PI<<'\ 0' ; cout<<buf<<endl; char *pstr=out1.str(); cout<<pstr<<endl; } 执行该程序输出结果如下: Buf:a=50;a=60;a=70;a=80;a=90;a=100; The value of pi is 3.14159265 The value of pi is 3.14159265 2、 istrstream 类的构造函数: 有两个: istrstream::istrstream(char *s); istrstream::istrstream(char *s,int n); 参数说明:⒈第一个参数 s 是一个字符指针或字符数组,使用该流来初始化要创建的流对象。 ⒉ n 表示使用前 n 个字符来构造流对象。 功能:使用所指定的串的全部内容(或前 n 个字符)来构造流对象。 例 14 :分析下列程序的输出结果: #include<iostream.h> #include<strstrea.h> void main() { char buf[]=”123 45.67” ; int a; double b; istrstream ss(buf); ss>>a>>b; cout<<a+b<<endl; } 执行结果: 168.67 例 15 :分析下列程序的输出结果: #include<iostream.h> #include<strstrea.h> void main() { char buf[]=” 12345” ; int I,j; istrstream s1(buf); s1>>I; istrstream s2(buf,3); s2>>j; couit<<I+j<<endl; } 执行结果: 12468 |
|
![]() ![]() |