例:“写”字符数组
#include<iostream> #include <strstream> using namespace std; struct student { int num; char name[20]; float score; }; int main( ) { student stud[3]= {1001,"Li",78,1002,"Wang",89.5,1004,"Fun",90}; char c[50]; //用户定义的字符数组 ostrstream strout1(c,30); //建立输出字符串流,与数组c建立关联,缓冲区长30 for(int i=0; i<3; i++) //向字符数组c写3个学生的数据 strout1<<stud[i].num<<stud[i].name<<stud[i].score; strout1<<ends; //ends是C++的I/O操作符,插入一个′\\0′ cout<<"array c:"<<c<<endl; //显示字符数组c中的字符 ostrstream strout2(c,40); //这时,c将被重写 for(int i=0; i<3; i++) strout2<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<" "; strout2<<ends; //ends是C++的I/O操作符,插入一个′\\0′ cout<<"array c:"<<c<<endl; //显示字符数组c中的字符 return 0; }
以字符串流为中介交换数据
#include <strstream> #include<iostream> using namespace std; int main( ) { char c[50]="12 34 65 -23 -32 33 61 99 321 32"; int a[10],i,j,t; cout<<"array c:"<<c<<endl;//显示字符数组中的字符串 istrstream strin(c,sizeof(c)); //建立输入串流对象strin并与字符数组c关联 for(i=0; i<10; i++) strin>>a[i]; //从字符数组c读入10个整数赋给整型数组a cout<<"array a:"; for(i=0; i<10; i++) cout<<a[i]<<" "; //显示整型数组a各元素 cout<<endl; for(i=0; i<9; i++) //用起泡法对数组a排序 for(j=0; j<9-i; j++) if(a[j]>a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } ostrstream strout(c,sizeof(c)); //建立输出串流对象strout并与字符数组c关联 for(i=0; i<10; i++) strout<<a[i]<<" "; //将10个整数存放在字符数组c strout<<ends; //加入′\\0′ cout<<"array c:"<<c<<endl; //显示字符数组c return 0; }
时间: 2024-09-19 19:29:40