C++程序设计趣题:标准输入输出

标准输入输出类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);
		};
	}

【疑问】

  1. 类成员若写成istream MyCin::in则VS上编译不通过,报错
    error C2280: “std::basic_istream<char,std::char_traits>::basic_istream(const std::basic_istream<char,std::char_traits> &)”: 尝试引用已删除的函数
    此处为何报错?

  2. 没有想到很好的停止输入的办法,于是用了粗暴的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
【自编代码段】
需要实现的功能:

  1. 以cin为实参的构造函数;
  2. *和++的重载

T* pt;
	istream &in;
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;
	}
	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值