[Wylug-help] Re: C++ Programming Question.

Dave Whiteley d.l.whiteley at ee.leeds.ac.uk
Tue Aug 24 18:09:06 BST 2004


On Tue, Aug 24, 2004 at 04:46:01PM +0100, Neil Pilgrim wrote:
>
> What was the type of infile and outfile? Would it be possible to do:
>
> istream *in = new ifstream("somefile");
>
> when you want a file and
>
> istream *in = cin;
>
> when using stdin? (possibly with '&cin'...I've not tested)
>
> I thought we used this at some point, and I don't see why it shouldn't
> work...unless you don't want the students to get confused over the use of
> istream, which they haven't come across explicitly IIRC.
>
> TBH I always wondered why the code used that fileno() method, instead of
> the above.
>
> --
> Neil
>
>



That was my first thought when I wrote it, years ago.

I have just re-tried it ...  (I have marked the line numbers.)

################################################################

#include <fstream.h>
#include <iostream.h>


int main(void)
{
  char * infilename = 0;    /* the name of the input file */
  char * outfilename = 0;   /* the name of the output file */
  ifstream   *infile; /* The input file stream; default stdin */
  ofstream   *outfile; /* The output file stream; default stdout */


  if(infilename)
    {

      infile = new ifstream(infilename); /* Allocate an infile stream */
      /*infile.open(infilename, ios::in);*/ /* Try to open the file (called infilename) */

      if(infile.is_open()==false)  /* It wasn't able to open the file */
	{
	  cerr << "There is no file called " << infilename << endl;
	  cerr << "Exiting program \n\n";
	  retval = false;
	  exit(1);
	  /* Output a message then exit (stop the program) */
	  /* This should be a return and output of the help file in the final version */
    	}
    }
  else
    { /* Otherwise, there is no input filename specified so we open 'stdin' (ie from the keyboard */
      /*infile = new ifstream(fileno(stdin));*/
<32>      infile = cin;

    }

  if(outfilename)
    {
      if(!(outfile = new ofstream(outfilename)))
	{
	  cerr << "Cannot open file " << outfilename << "\n";
	  exit(1);
	}
    }
  else
    {
<46>      outfile = cout;
    }

  return 0;
}


#######################################################

There may be other nasties in there, but when I compile I get

testfile.cpp:32: error: invalid conversion from `void*' to `std::ifstream*'
testfile.cpp:46: error: invalid conversion from `void*' to `std::ofstream*'


Would a type cast be valid?  What would be the syntax?

Dave


--

Dave Whiteley
d.l.whiteley at ee.leeds.ac.uk
Phone +44 (0)113 343 2059
School of Electronic and Electrical Engineering
The University of Leeds. Leeds, LS2 9JT,  UK




More information about the Wylug-help mailing list