主要代码
// ---------------------------------------------------------------------------
/*
字符串流有三个对象:
输出流:ostrstream
输入流:istrstream
输入输出流: strstream
字符串流在C++ Builder中来说,就是个鸡肋
*/
#include <iostream>
#include <strstream>
using namespace std;
#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
// ---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) {
}
// ---------------------------------------------------------------------------
// 用字符串流,示例一个随机数组冒泡排序
void __fastcall TForm1::Button1Click(TObject *Sender) {
Memo1->Text = "C++ Builder 示例字符串流";
int randa[10];
char buf[50];
int arr[10];
register int i, j;
srand((unsigned int) time(0)); // 初始随机种子
for (i = 0; i < 10; i++) {
randa[i] = rand() % 1000; // 随机数
}
ostrstream ostrr(buf, sizeof(buf));
for (i = 0; i < 10; i++) {
ostrr << randa[i] << " ";
}
UnicodeString s;
for (i = 0; i < 50; i++) {
s = s + (UnicodeString) buf[i];
}
Memo1->Lines->Add("随机数:" + Trim(s));
istrstream istr(buf, sizeof(buf));
for (i = 0; i < 10; i++) {
istr >> arr[i];
}
s = "";
for (i = 0; i < 10; i++) {
s = s + " " + (UnicodeString) arr[i];
}
Memo1->Lines->Add("整型数:" + s);
for (i = 0; i < 10; i++) { // 冒泡算法排序
for (j = 0; j < 10 - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
ostrstream ostr(buf, sizeof(buf));
for (i = 0; i < 10; i++) {
ostr << arr[i] << " ";
}
s = "";
for (i = 0; i < 50; i++) {
s = s + (UnicodeString) buf[i];
}
Memo1->Lines->Add("排序后:" + Trim(s));
}
// ---------------------------------------------------------------------------
输出效果