字串流不以磁碟檔案為對象,而是以記憶體中的字元陣列為輸入/輸出目標。資料以 ASCII 碼形式在記憶體緩衝區與字元陣列間流動,因此也稱為記憶體流。其操作方式與檔案流、標準輸入輸出流高度一致,極大降低學習成本。
定義於 <strstream> 標頭檔:
char buffer[50]; ostrstream strout(buffer, 30); // 緩衝區 30 位元組,關聯 buffer
char data[] = "12 34 56"; istrstream strin(data); // 全部內容 istrstream strin2(data, 5); // 僅前 5 字元
char buf[100]; strstream strio(buf, sizeof(buf), ios::in | ios::out);
ends 插入 '\0')struct Student { int num; char name[20]; float score; };
Student stud[3] = {{1001,"Li",78}, {1002,"Wang",89.5}, {1004,"Fun",90}};
char c[50];
ostrstream strout(c, sizeof(c));
for (int i=0; i<3; ++i)
strout << stud[i].num << ' ' << stud[i].name << ' ' << stud[i].score;
strout << ends; // 必須加結束符
cout << "array c: " << c << endl;
// 輸出: 1001 Li 78 1002 Wang 89.5 1004 Fun 90
char c[50] = "12 34 65 -23 -32 33 61 99 321 32";
int a[10];
istrstream strin(c, sizeof(c));
for (int i=0; i<10; ++i) strin >> a[i]; // 自動按空格分隔讀取整數
// 冒泡排序
for (int i=0; i<9; ++i)
for (int j=0; j<9-i; ++j)
if (a[j] > a[j+1]) swap(a[j], a[j+1]);
ostrstream strout(c, sizeof(c));
for (int i=0; i<10; ++i) strout << a[i] << ' ';
strout << ends;
cout << "sorted: " << c << endl;
// 輸出: -32 -12 32 33 34 61 65 99 321
字串流是記憶體中的「臨時倉庫」,以 ASCII 形式存儲多型別資料,讀寫靈活、速度極快、無檔案管理開銷。掌握它能優化暫存資料處理、字串解析、序列化等場景,是 C++ 高效程式設計的利器。