标准输入输出类iostream是C++风格的一大亮点,有关知识点和模板类等结合可以提出有趣的问题。以下是一些笔者遇到的有趣例题,记录下来以备查询;同时附AC的自编代码段,欢迎大家提出优化的批评建议。
目录
例题一 “你真的搞清楚为啥 while(cin >> n) 能成立了吗?”
例题二 “山寨版istream_iterator”
例题一 “你真的搞清楚为啥 while(cin >> n) 能成立了吗?”
【描述】补充下列程序实现给定的输入输出:
#include <iostream>
using namespace std;
class MyCin
{
//**************************
//****在此处补充你的代码****
//**************************
};
int main()
{
MyCin m;
int n1,n2;
while( m >> n1 >> n2)
cout << n1 << " " << n2 << endl;
return 0;
}
【输入】多组数据,每组一行,是两个整数
【输出】对每组数据,原样输出;当碰到输入中出现-1 时,程序结束;输入中保证会有 -1。
【实例输入】
12 44
344 555
-1
2 3
【实例输出】
12 44
344 555
【来源】OJ
【自编代码段】
istream& in;
public:
MyCin() :in(cin) { ; }
~MyCin() { ; }
friend istream& operator>>(MyCin& in_, int &n) {
int temp = 0;
in_.in >> temp;
if(temp != -1){n = temp; return in_.in;}
else {
exit(0);
};
}
【疑问】
-
类成员若写成
istream MyCin::in
则VS上编译不通过,报错
error C2280: “std::basic_istream<char,std::char_traits>::basic_istream(const std::basic_istream<char,std::char_traits> &)”: 尝试引用已删除的函数
此处为何报错? -
没有想到很好的停止输入的办法,于是用了粗暴的
exit(0);
。
更好的方法是跳出while循环,即需要m>>n1>>n2
表达式的值为false,笔者不知道这在iostream中是如何实现的。
例题二 “山寨版istream_iterator”
【描述】
模仿C++标准模板库istream_iterator用法,实现CMyistream_iterator使得程序按要求输出。
#include <iostream>
#include <string>
using namespace std;
template <class T>
class CMyistream_iterator
{
//****************************
//*****在此处补充你的代码*****
//****************************
};
int main()
{
int t;
cin >> t;
while( t -- ) {
CMyistream_iterator<int> inputInt(cin);
int n1,n2,n3;
n1 = * inputInt; //读入 n1
int tmp = * inputInt;
cout << tmp << endl;
inputInt ++;
n2 = * inputInt; //读入 n2
inputInt ++;
n3 = * inputInt; //读入 n3
cout << n1 << " " << n2<< " " << n3 << " ";
CMyistream_iterator<string> inputStr(cin);
string s1,s2;
s1 = * inputStr;
inputStr ++;
s2 = * inputStr;
cout << s1 << " " << s2 << endl;
}
return 0;
}
【输入】第一行是整数t,表示有t组数据;每组数据一行,三个整数加两个字符串。字符串不含空格。
【输出】对每组数据,输出二行:在第一行输出第一个数,第二行原样输出输入的内容。
【实例输入】
2
79 90 20 hello me
12 34 19 take up
【实例输出】
79
79 90 20 hello me
12
12 34 19 take up
【来源】OJ
【自编代码段】
需要实现的功能:
- 以cin为实参的构造函数;
- *和++的重载
T* pt;
istream ∈
public:
CMyistream_iterator(istream& in_):in(in_) {
pt = new T;
in >> *pt;
return;
}
~CMyistream_iterator() {
if(pt) { delete pt; pt = NULL; }
return;
}
void operator++(int) {
in >> *pt;
return;
}
T operator*() {
return *pt;
}