自己设计和编写5个(用成员函数和操控符的程序各至少5个,2类程序可以实现同样的功能)以上的小程序测试使用ios类的所有成员函数和使用(所有)操控符进行格式化输入/输出的方
时间: 2024-02-15 09:05:17 浏览: 23
案
程序1:使用成员函数实现输入和输出
```c++
#include <iostream>
#include <string>
using namespace std;
class ios_test {
public:
void input() {
cout << "请输入字符串:";
getline(cin, str);
}
void output() {
cout << "输出的字符串为:" << str << endl;
}
private:
string str;
};
int main() {
ios_test t;
t.input();
t.output();
return 0;
}
```
程序2:使用成员函数实现格式化输出
```c++
#include <iostream>
#include <iomanip>
using namespace std;
class ios_test {
public:
void output() {
cout << "使用setw()实现对齐" << endl;
cout << setw(10) << left << "left" << setw(10) << right << "right" << endl;
cout << setw(10) << internal << "internal" << setw(10) << setfill('*') << "setfill" << endl;
cout << "使用setprecision()实现精度控制" << endl;
cout << setprecision(2) << 3.1415926 << endl;
cout << setprecision(5) << 3.1415926 << endl;
cout << "使用setiosflags()实现控制位的设置" << endl;
cout << setiosflags(ios::fixed) << setprecision(2) << 3.1415926 << endl;
cout << setiosflags(ios::scientific) << setprecision(2) << 3.1415926 << endl;
}
};
int main() {
ios_test t;
t.output();
return 0;
}
```
程序3:使用操控符实现输入和输出
```c++
#include <iostream>
#include <string>
using namespace std;
class ios_test {
public:
void input() {
cout << "请输入字符串:";
cin >> str;
}
void output() {
cout << "输出的字符串为:" << str << endl;
}
private:
string str;
};
int main() {
ios_test t;
t.input();
t.output();
return 0;
}
```
程序4:使用操控符实现格式化输出
```c++
#include <iostream>
#include <iomanip>
using namespace std;
class ios_test {
public:
void output() {
cout << "使用setw()实现对齐" << endl;
cout << setw(10) << left << "left" << setw(10) << right << "right" << endl;
cout << setw(10) << internal << "internal" << setw(10) << setfill('*') << "setfill" << endl;
cout << "使用setprecision()实现精度控制" << endl;
cout << fixed << setprecision(2) << 3.1415926 << endl;
cout << fixed << setprecision(5) << 3.1415926 << endl;
cout << "使用setiosflags()实现控制位的设置" << endl;
cout << fixed << setprecision(2) << 3.1415926 << endl;
cout << scientific << setprecision(2) << 3.1415926 << endl;
}
};
int main() {
ios_test t;
t.output();
return 0;
}
```
程序5:使用成员函数和操控符实现输入和输出
```c++
#include <iostream>
#include <string>
using namespace std;
class ios_test {
public:
void input() {
cout << "请输入字符串:";
getline(cin, str);
}
void output() {
cout << "输出的字符串为:" << str << endl;
}
friend ostream& operator<<(ostream& os, const ios_test& t) {
os << "输出的字符串为:" << t.str << endl;
return os;
}
friend istream& operator>>(istream& is, ios_test& t) {
cout << "请输入字符串:";
getline(is, t.str);
return is;
}
private:
string str;
};
int main() {
ios_test t1, t2;
t1.input();
t1.output();
cin >> t2;
cout << t2;
return 0;
}
```