第8章C++输入输出类层次.ppt

第8章C输入输出类层次课件

8.7 字符串流(包含在strstrea中) I/O流库有两个类:ostrstream 和 istrstream: ostrstream类是从ostream类派生出来的 用来将不同类型的信息格式化为字符串,并放到一个字符数组中 istrstream类是从istream类派生出来的 用来将文本项转换为变量所需要的内部格式 将一个字符串内的数字字符转换成二进制形式存放在某种类型的对象中 将一个二进制数转换成字符存储在一个字符数组对象中 ostrstream类的构造函数 两个构造函数,它们的原型分别是: ostrstream::ostrstream( ); ostrstream::ostrstream(char *s, int n, int mode = ios::out); 缺省为out方式,还可选用ate和app方式。 进行插入操作时,并不在输出流中的末尾自动添加空字符 功能:建立存储所插入的数据的数组对象 Ostrstream 类还提供了如下的成员函数: int ostrstream::pcount( ): 返回流中当前已插入的字符的个数 char *ostrstream::str( ): 返回标识存储串的数组对象的指针值 例:构造函数 #include iostream #include fstream #include strstrea.h const int N=80; void main( ) {?? char buf[N]; ??? ostrstream out1(buf, sizeof(buf)); ??? int a = 50; ??? for(int i=0; i6; i++, a+= 10)?????? out1 a= a ;; ??? out1 \0“;??? cout Buf: buf endl; ??? double pi = 3 例:构造函数 ??? out1.setf(ios::fixed | ios::showpoint); ??? out1.seekp(0); ??? out1 The value of pi= pi \0; ??? cout buf endl; ??? char *pstr = out1.str( ); // str( ) 返回流 out1 的首址 ??? cout pstr endl; } ANS: Buf:a=50;a=60;a=70;a=80;a=90;a=100; The value of pi is 3The value of pi is 3istrstream类的构造函数 两个构造函数,它们的原型分别是: istrstream::istrstream(char*s); istrstream::istrstream(char*s,int n); 功能: 使用所指定的串的全部内容(串中前n个字符 )来构造流对象 istrstream类对象可以是有名也可以是无名的。例如: char s[ ]=1234; istrstream(s,3); //对象是无名的 istrstream ss (s,3); //对象是有名的 例 构造函数 #include iostream #include strstrea.h void main( ) {?? char buf[ ] = 123 45.67; ??? int a; ??? double b; ??? istrstream ss(buf); ??? ss a b; // a = 123 b = 45.67 ??? cout a + b endl; } Ans: 168.67 例 #include iostream #include strstrea.h void main( ) {? char buf[ ] = 12345; ??? int i, j; ??? istrstream s1(buf); ??? s1 i; // i = 12345 ??? istrstream s2(buf, 3); ??? s2 j; // j = 123 ??? cout i + j endl; } Ans: 12468 int main() { char str[10]; int i=0; cout输入一个字符串(最多9

文档评论(0)

1亿VIP精品文档

相关文档