待解决输入istream_iterator

山寨版 istream_iterator

输入

第一行是整数t,表示有t组数据,每组数据一行,三个整数加两个字符串。字符串是不含空格的。

输出

对每组数据,输出二行,在第一行输出第一个数,第二行原样输出输入的内容

 

原来的思路是 ,定义一个数组,先把数据都读进来,然后进行读或移动指针操作。然后发现,数据读取始终有问题!!本来的类模板是这样写的,其实这样写的确有问题,比如说问题是要求先整数再字符串,但如果是先字符串再整数,while(cin>>n)压根没法判断字符串什么时候结束。但我觉得纳闷的还不是这里,而是,正确读完整数后,字符串压根读不了

class CMyistream_iterator
{
    T input[5];
    int index;
    public:
        CMyistream_iterator(istream & cin){
            int i = 0;
            T n;
            while(cin >> n){
                input[i] = n;
                ++i;
            }
            getchar();
            index = 0;
        }    
        CMyistream_iterator operator++(int){
            index += 1;
            return *this;
        }
        T & operator*(){
            return *(input + index);
        }
};

 

 

后来就去看大家怎么写,发现大家真是简单粗暴,需要输出下一个了才去读取,深得临时抱佛脚的宗旨。

#include <iostream>
#include <string>

using namespace std;
template <class T>
class CMyistream_iterator
{
    T x;
    int index;
    istream &i;
    public:
        CMyistream_iterator(istream & i0):i(i0){
            i >> x;
        }    
        void operator++(int){
            i >> x;
        }
        T operator*(){
            return x;
        }
};



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;  
}

 

猜你喜欢

转载自www.cnblogs.com/fanmu/p/10664364.html
今日推荐