// c_datastructure.cpp : 定义控制台应用程序的入口点。
//
// C++字符串流的练习demo
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<strstream>
#include<iomanip>
#include<string>
using namespace std;
struct Student {
int num;
char name[20];
int score;
};
void bubbleSort(int A[], int n) {
// 逐行扫描直到有序,同时设置标志位
for (bool sorted = false; sorted = !sorted; n--) {
// 自左向右逐个检查相邻元素
for (int i = 0; i < n; i++) {
// 若为逆序,则交换
if (A[i - 1] > A[i]) {
swap(A[i - 1], A[i]);
// 清楚全局有序标志位
sorted = false;
}
}
}
}
int main()
{
cout << "************" << endl;
char c[50] = "12 33 25 67 123 -12 -4 -32 65 23";
int a[10], i, j, t;
// 打印数组c原来的内容
cout << "Array c: " << c << endl;
// 建立字符串流输入对象并且将对象strin和字符数组c关联
istrstream strin(c,sizeof(c));
// 从字符数组c读入10个整数并且赋值给整型数组a
for (i = 0; i < 10; i++) strin >> a[i];
// 打印数组a的内容
cout << "Array a: ";
for (i = 0; i < 10; i++) {
cout << a[i] << " ";
}
cout << endl;
bubbleSort(a, 10);
// 建立字符串流输出对象并且将对象strout和字符数组c关联
ostrstream strout(c, sizeof(c));
// 将排序好的10个数组元素存放在字符数组c中
for (i = 0; i < 10; i++) {
strout << a[i] << " ";
}
// 加入'\0'
strout << ends;
cout << "Array c: " << c << endl;
return 0;
}
C++字符串流练习
最新推荐文章于 2023-06-18 19:30:17 发布