C++: I/O流詳解(三)——串流
阿新 • • 發佈:2017-11-02
name namespace 轉換 pac end 成員 col logs nbsp
一、串流
串流類是 ios 中的派生類
C++的串流對象可以連接string對象或字符串
串流提取數據時對字符串按變量類型解釋;插入數據時把類型 數據轉換成字符串
串流I/O具有格式化功能
例:
1 #include <iostream> 2 #include <sstream> 3 #include <string> 4 #include <strstream> 5 6 using namespace std; 7 //?什麽鬼? 8 /*從輸入串流對象提取數據 9 int main(){ 10 string testStr("Input test 256*0.5");11 string s1, s2, s3; 12 double x, y; 13 istringstream input(testStr); //用string對象構造串流對象 14 input>> s1>> s2>> x>> s3>> y; 15 cout<< s1<< ends<< s2<< ends<< x<< s3<< y<< "="<< x*y<< endl; 16 return 0;17 } 18 */ 19 20 //向輸出串流對象插入數據 21 /* 22 int main(){ 23 ostringstream Output; 24 double x, y; 25 cout<< "Input x:"; 26 cin>> x; 27 cout<< "Input y:"; 28 cin>> y; 29 Output<<x<<"*"<<y<<"="<<x*y<<endl; 30 cout<<Output.str();31 return 0; 32 } 33 */ 34 35 //向輸出串流對象插入數據 36 int main(){ 37 char buf[80]; 38 ostrstream Output(buf, sizeof(buf));//對Output的數據成員初始化 39 double x, y; 40 cout<< "Input x:"; 41 cin>> x; 42 cout<< "Input y:"; 43 cin>> y; 44 Output<<x<<"*"<<y<<"="<<x*y<<endl; 45 cout<<Output.str(); 46 return 0; 47 }
C++: I/O流詳解(三)——串流