assigning one ifstream to another ifstream

Apr 26, 2008 at 2:48am
Hi I am Aden and Iam currently working on a C++ assignment.

everything was working fine until i tried to assign one ifstream object to another ifstream object.

This is an example of the code.

1
2
3
4
ifstream one("some.txt");
ifstream two;

two = one;


Can you simply not use ifstream objects in this manner?
Apr 26, 2008 at 3:27am
from my understanding, no.
this is because of the system of variable use. ifstream one is not a variable, and nor is ifstream two.
variables are something like int, float, etc. They can be added, subtracted and equaled, but not non-variables.
however, you could just write
1
2
std::ifstream one("file1.txt");
std::ifstream two("file1.txt");

note how i assigned ifsteam two to the same file as ifstream one.
just out of curiosity, why do you need to assign one file to two inputs? couldnt you just keep using ifstream one?
Last edited on Apr 26, 2008 at 3:28am
Apr 26, 2008 at 3:42am
Iam trying to make the ifstream a global variable so basically my 'two' is declared in the header file and my 'one' opens the file and then I want to assign the 'one' two the 'two' so that other methods in the class can use the global variable. I am getting confused because you can do that kind of thing in Java, I don't know how to do it in C++.
Apr 26, 2008 at 3:45am
then cant you just declare two to the same file that one contains? like what i did in the example? or why dont you just stay with a global variable for all of it and not even bother with the ifstream two?
alternatively, you could declare two in the header file, get one to reference the header file and just keep using two after that?
Apr 26, 2008 at 3:52am
I tried to just use the global ifstream object but I don't seem to be able to reference it for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef A2Files
#define A2Files

#include <iostream>

#include <string>
using std::string;

#include <fstream>
using std::ifstream;

class a2Files
{
public:
	a2Files( string filename ); 
	void setFile( string filename );
	void readLine();

private:
	ifstream myIFile; //filestream object
};

#endif 


and then

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void a2Files::setFile( string filename )
{
	myIFile(filename.c_str());
		
	if(myIFile.fail())
	{
    cerr << "Could not open \""<< filename << "\""
         << ":reason " << strerror(errno) 
         << endl;
    exit(1);
	}
	else
	{
	cout << "File opened successfully." << endl;
		
	}
}


I hope this makes sense
Apr 27, 2008 at 1:32am
i still dont understand what you are trying to do..
the top code is your header file, no?
then where are you referencing your ifstream in the second block of code?
Topic archived. No new replies allowed.