c++istreamgeneric-function

Std::istream& as function parameter


What is the best way to make a program that reads the elements from the input until the EOF and returns the container of read elements? This is what I have to do

p.h file:

#pragma once
#include <list>
#include <iostream>

typedef double Element;

template<typename T>
std::list<T> read(std::istream& u);

This is what I tried:

#pragma once
#include <list>
#include <iostream>

typedef double Element;

template<typename T>
std::list<T> read(std::istream& u){

  while(u){
   
   std::list<T> l;
   l.push_front(u);
   return l;

  }

}


p.cpp file:

#include "p.h"
#include <iostream>



int main(){
  double u;
  std::cin>>u;
 
  std::list<double> l=read(u);




}

What exactly do I have to pass as an argument the a main function? I tried passing an std::cin but it doesn't work. It could also be because read function is not defined properly. Also I don't understand what's the point of typedef being double if we are making generic functions.


Solution

  • When you do l.push_front(u) you are trying to store the istream in the list. You need to read a T from the stream and store that instead. Also note that you need to declare l outside the loop in order to be able to read all values and then return l:

    template<typename T>
    std::list<T> read(std::istream& u){
      T tmp;
      std::list<T> l;
    
      while(u >> tmp){
         l.push_front(tmp);
      }
    
      return l;
    }
    

    Then specify the type you want to read from the stream by supplying it as a template parameter:

    int main(){
      auto l=read<double>(std::cin);
    }