您现在的位置: 中国男护士网 >> 考试频道 >> 计算机等级 >> 二级辅导 >> C十十 >> 辅导 >> 正文    
  二级C++输入输出流:字符串流 【注册男护士专用博客】          

二级C++输入输出流:字符串流

www.nanhushi.com     佚名   不详 

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

 

文章录入:杜斌    责任编辑:杜斌 
  • 上一篇文章:

  • 下一篇文章:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
     

    联 系 信 息
    QQ:88236621
    电话:15853773350
    E-Mail:malenurse@163.com
    免费发布招聘信息
    做中国最专业男护士门户网站
    最 新 热 门
    最 新 推 荐
    相 关 文 章
    没有相关文章
    专 题 栏 目