C++字串流
字元流概念:字串(string)也可以看作字元流。可以用輸入輸出操作來完成串流的操作。串流與記憶體相關,所以也稱記憶體流。
串流類包括ostrstream、istrstream、strstream,它們在<strstrea.h>中說明。串流類物件可以儲存字元,也可以儲存整數、浮點數。串流類物件採用文字方式。
其建構函式常用下面幾個:
istrstream::istrstream(const char * str);
istrstream::istrstream(const char * str,int);
ostrstream::ostrstream(char *,int,int=ios::out);
strstream::strstream(char *,int,int);
其中第二個引數說明陣列大小,第三引數為檔案開啟方式。
【例9.12】字串流類的應用。
#include<strstream>
#include<iostream>
#include<cstring>
using namespace std;
int main(){
int i;
char str[36]="This is a book.";
char ch;
istrstream input(str,36); //以串流為資訊源
ostrstream output(str,36);
cout<<"字串長度:"<<strlen(str)<<endl;
for(i=0;i<36;i++){
input>>ch; //從輸入裝置(串)讀入一個字元,所有空白字元全跳過
cout<<ch; //輸出字元
}
cout<<endl;
int inum1=93,inum2;
double fnum1=89.5,fnum2;
output<<inum1<<' '<<fnum1<<'/0'; //加空格分隔數字
cout<<"字串長度:"<<strlen(str)<<endl;
istrstream input1(str,0); //第二引數為0時,表示連線到以串結束符終結的串
input1>>inum2>>fnum2;
cout<<"整數:"<<inum2<<'/t'<<"浮點數:"<<fnum2<<endl; //輸出:整數:93 浮點數:89.5
cout<<"字串長度:"<<strlen(str)<<endl;
return 0;
}