Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading