Problems with streams

I actually have a few problems in one with this. First of all, can I make a pointer and assign it to an ifstream? Problem 2: Can I pass a stream to a function.

I need to use a stream in a function, but I thought it might be more elegant to pass the function a pointer that is directed at a stream. The program with the problem is listed below:

Thanks for the help!!

#include <iostream.h>
#include <fstream.h>
#include "mystructs.h"
//this has a "dog" structure with two variables, size and training respectively
using namespace std;
void dog_info_output (int dog_num, ifstream* in_stream);
//In this function def I want to send a pointer to an ifstream and call the pointer in_stream. this function uses an int to iterate a file with two chars of info per dog, works fine without passing a pointer by a different method, but I want to figure out if this one is possible.
int main() {
ofstream out_stream;
ifstream in_stream;
out_stream.open("dogout.txt", ios::app);
in_stream.open("dogout.txt");
int num_dogs;
int i;
cout << "How many dogs? ";
cin >> num_dogs;
cout << endl;
//this creates a pointer called dogarray to a dynamic array of pointers, the same size as num_dogs entered before
dog** dogarray = new dog*[num_dogs];
char _bool = 'F';
for (i = 0; i < num_dogs; i++) {
char size;
char training;
cout << "Is the dog big (b) or small (s)? ";
cin >> size;
cout << '\n' << "Is the dog trained (Y) or not (N)";
cin >> training;
cout << endl;
dogarray[i] = new dog;
dogarray[i]->size = size;
dogarray[i]->training = training;
out_stream << dogarray[i]->size << dogarray[i]->training;
}
ifstream *in_stream_func = in_stream;
//I want to designate a ifstream pointer called in_stream_func and have it point to in_stream

int dognum;
cin >> dognum;
dog_info_output (2 * (dognum - 1), *in_stream_func);
out_stream.close ();
in_stream.close ();


delete []dogarray;

return 0;
}

void dog_info_output (int dognum, ifstream* in_stream) {
char next;
for (dognum; dognum >= 0; dognum--) {
in_stream.get(next);
if (dognum == 0) {
cout << "This dog's size is: " << next << endl;
in_stream.get(next);
cout << "Training: " << next << endl;
}
}
return;
}
Last edited on
Yes and yes, but I would suggest just passing it by reference instead.
Thanks for the advice, I'll look into that for sure!! For now, can anyone help me figure out how to fix my above program by using a pointer to the stream and then passing the pointer to a function?

After I figure this out I'll re-write the program using references instead, I just want to make sure I know how to do this. Right now everything works ok except the in_stream.get statement in my dog_info_output function.

Thanks again all!!
Topic archived. No new replies allowed.