描述
请补齐下面程序,使得补齐后的程序,对于下面指定的输入数据,能产生指定的输出。
#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;
int tmp = * inputInt;
cout << tmp << endl;
inputInt ++;
n2 = * inputInt;
inputInt ++;
n3 = * inputInt;
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组数据。
每组数据由三个整数和两个字符串组成。整数都是小于220的正整数,字符串中间没有空格
输出
对每组输入数据,输出两行。
第一行是输入的第一个整数。
第二行依次输出输入的各项,用逗号","分隔。
样例输入
2
79 90 20 hello me
21 375 45 Jack good
样例输出
79
79,90,20,hello,me
21
21,375,45,Jack,good
一开始看到这句话
istream_iterator模版使用说明:
其构造函数执行过程中就会要求输入
想当然的以为要在构造函数里面完成每一次实例化的输入 尝试了很多方法都没有成功ORZ
后来仔细想了想istream_iterator这个类是怎么实现的 才注意到只需在重载的++函数中输入后续数据就可以了。。不需要考虑输入数据到底有几个
#include <iostream>
#include <string>
using namespace std;
template <class T>
class CMyistream_iterator
{
public:
CMyistream_iterator(istream & iss):is(iss)
{
is>>a;//这里直接用cin也可以 为了一致性还是写成这样吧
}
T operator *()
{
return a;
}
void operator ++(int)
{
is>>a;//这里直接用cin也可以 为了一致性还是写成这样吧
}
private:
T a;
istream & is;
};
int main()
{
int t;
cin>>t;
while (t--)
{
CMyistream_iterator<int> inputInt(cin);
int n1,n2,n3;
n1 = * inputInt;
int tmp = * inputInt;
cout << tmp << endl;
inputInt ++;
n2 = * inputInt;
inputInt ++;
n3 = * inputInt;
cout << n1 << "," << n2<< "," << n3 << ",";
CMyistream_iterator<string> inputStr(cin);
string s1,s2;
s1 = * inputStr;
inputStr ++;
s2 = * inputStr;
cout << s1 << "," << s2 << endl;
}
return 0;
}
为了保证上面注释中说的一致性
又多声明了一个 istream类is
看起来是不是很奇怪
1、直接声明不可以吗 ?为什么要声明一个引用?
2、并且这个引用还没有给出初始值!
原因貌似是 IO 类只能声明为引用 不能直接声明 并且声明为引用的时候必须通过初始化列表来进行初始化